python: mutating the copy of a list changes the original?

前端 未结 1 1450
孤独总比滥情好
孤独总比滥情好 2021-01-23 01:11

So until now, i was under the assumption that if you have for example:

L = [1,2,3]
L2 = L1
L2.append(5)

both L and L2 would be affected by the

相关标签:
1条回答
  • 2021-01-23 01:41

    Slicing is a shallow copy. A copy created by slicing will contain new references to the old elements of the original list; if the original list contained mutable objects such as more lists, the copy will contain references to those same lists. You can use copy.deepcopy to try to get around this, or loop through your original list and slice-copy the elements into a new list. Be careful with copy.deepcopy, though; there's often some depth at which you want to stop making copies and keep the original elements.

    0 讨论(0)
提交回复
热议问题