Search code examples
pythoncollectionsdeque

Unexpected deque python behaviour


Why in the following assignment..

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

deque([])

returns a empty deque? I expect to retain data in a despite clearing the old deque.


Solution

  • a and d reference the same object. So if you clear it, it will be cleared for "both variables".

    You could check that by printing the identity of objects.

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

    Copy values by assignment is just possible for fundamental data types like int etc. If you deal with objects you have to copy it because the variables itself just holding a reference to the object.

    You could do that with

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

    or with

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

    which results in

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

    but then you will get two different objects in a and d which will differ after you use it.