Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 702
progloverfan Avatar asked Oct 21 '25 11:10

progloverfan


2 Answers

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.

like image 181
wenzul Avatar answered Oct 23 '25 01:10

wenzul


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)
like image 29
ekhumoro Avatar answered Oct 22 '25 23:10

ekhumoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!