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.
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.
The line:
a = d
does not create a copy - it just creates another name for the same object.
To create a copy, do this:
d = deque('abc')
a = deque(d)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With