问题
Just trying to understand the difference between shallow copies. Say I have a list:
lst = [1,2,3]
a = lst
b = lst[:]
Can someone please explain the difference between these shallow copy methods.
回答1:
The difference between a
and b
here is that a
is another reference to lst
, but b
is a reference to a new list. You can see this by modifying a
. It results that lst
is modified (since a
and lst
refer to the same object), but b
is not modified.
>>> lst = [1,2,3]
>>> a = lst
>>> b = lst[:]
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]
>>> a[0] = 3
>>> a
[3, 2, 3]
>>> b
[1, 2, 3]
>>> lst
[3, 2, 3]
However, although the operator [:]
creates a copy rather than a reference, it still creates a shallow copy, which means that the copy is only one layer deep. In particular, this means that if the elements of the list are more complex objects, those objects will not be copied, but will just be references to the same objects in the new list. This can be seen by trying the same thing with a list of lists:
>>> list2
[[0, 1], [2, 3]]
>>> list3 = list2
>>> list4 = list2[:]
>>> list3
[[0, 1], [2, 3]]
>>> list4
[[0, 1], [2, 3]]
>>> list4[0][0] = 2
>>> list3
[[2, 1], [2, 3]]
>>> list4
[[2, 1], [2, 3]]
Notice that modifying an element of the element of the list list4
also modifies list3
. This is because although they are different lists, their first elements both refer to the same list.
回答2:
Here is a simple example to show the difference. Basically, a=lst
is a pointer from a
to list lst
, so when you subsequently modify list a
list lst
is modified equally. a=lst[:]
is a copy of list lst
. So subsequent modification of a
has no effect on list lst
.
>>> a=[1,2,3]
>>> b=a
>>> b[1]='x'
>>> b
[1, 'x', 3]
>>> a
[1, 'x', 3]
>>> a=[1,2,3]
>>> c=a[:]
>>> c[1]='x'
>>> a
[1, 2, 3]
>>> c
[1, 'x', 3]
来源:https://stackoverflow.com/questions/61797651/what-is-the-difference-between-a-b-and-a-b