Python deque unexpected behavior
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.
source to share
>>> 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
source to share