Copying a list using [:] or copy () in python is shallow?

Let's say I have a list awith some values, and I did b = a[:]. Then changing the contents of the list bwill not change the list aaccording to what I read. Thus, this means that it is a deep copy. But the python documentation still treats this as a shallow copy. Can someone clear this for me?

+4
source share
4 answers

To demonstrate what a shallow copy means:

a = [ [1,2], [3,4,5] ]
b = a[:]  # make a shallow copy
a is b  # not the same object, because this is a copy
=> False
a == b  # same value, because this is a copy
=> True
a[0] is b[0]  # elements are the *same objects*, because this is a *shallow* copy
=> True

A change in structure awill not be reflected in b, because this is a copy:

a.pop()
len(a)
=> 1
len(b)
=> 2

: , a ( a) , b, b , a.

a[0][0] = 'XYZ'
b[0]
=> ['XYZ', 2]
+7

python docs

(, , ):

, ( ) , . , , , .

/, -. Deep copy / -.

+5

"b" "a" , .

, , a. , b, , .

>>> class Mutable(object):
...     def __init__(self, x):
...         self.x = x
...     def __repr__(self):
...         return 'Mutable({})'.format(self.x)
...
>>> a = [Mutable(1), Mutable(2)]
>>> b = a[:]
>>> del b[1]  # Doesn't affect a
>>> a
[Mutable(1), Mutable(2)]
>>> b[0].x = 5  # Visible through a
>>> a
[Mutable(5), Mutable(2)]
+1

"b" "a" , . , .

No, it is not. A shallow copy differs from a deep copy in whether the copied values ​​are copied or not.

In your case, the list is copied, but the two resulting lists will contain the same objects. Adding or removing a value in one list will not affect the other list, but changes to the contained object will be reflected.

+1
source

Source: https://habr.com/ru/post/1650610/


All Articles