Python deque unexpected behavior

Why in the next appointment ..

d = deque('abc')
a = d
d.clear()
print a

      

Deque ([])

returns an empty character? I expect to keep the data in a despite clearing the old deque.

+3


source to share


3 answers


a

and d

refer to the same object. So if you do clear

it, it will be cleared for "both variables".

You can verify this by typing the identity of the objects.

>>> id(a)
44988624L
>>> id(d)
44988624L

      

Copying values ​​as intended is possible only for basic data types such as int

, etc. If you are dealing with objects, you must copy them, because the variables themselves simply contain a reference to the object.

You can do it with

d = deque('abc')
a = deque('abc')

      



or

>>> import copy
>>> d = copy.copy(a)

      

that leads to

>>> id(a)
44988624L
>>> id(d)
44989352L

      

but then you will end up with two different objects in a

and d

that will be different after using it.

+5


source


Line:

a = d

      

doesn't create a copy - it just creates a different name for the same object.



To create a copy, do the following:

d = deque('abc')
a = deque(d)

      

+4


source


>>> from copy import deepcopy
>>> d = deque('abc')
>>> a = deepcopy(d)
>>> d.clear()
>>> a
deque(['a', 'b', 'c'])

      

Or you can use deque's

inline copy .

>>> d = deque('abc')
>>> a = d.__copy__
>>> a
<built-in method __copy__ of collections.deque object at 0x02437C70>
>>> a = d.__copy__()
>>> a
deque(['a', 'b', 'c'])
>>> d.clear()
>>> a
deque(['a', 'b', 'c'])

      


You were referencing the same object, so d

even a

cleared after clearing . To do this, you need to copy object d

to a

using the deepcopy method. Which copies the object for you, rather than referencing it

>>> id(a)
37976360
>>> id(d)
37976248

      

+1


source







All Articles