why is it that when i pop a dictionary in variable b, variable a does the same? And When i print variable a, the value is [{'b':2}]. How can i retain the value of variable a?
a=[{'a':1,},{'b':2,}]
b = a
b.pop(0)
why is it that when i pop a dictionary in variable b, variable a does the same? And When i print variable a, the value is [{'b':2}]. How can i retain the value of variable a?
a=[{'a':1,},{'b':2,}]
b = a
b.pop(0)
why is it that when i pop a dictionary in variable b, variable a does the same? And When i print variable a, the value is [{'b':2}]. How can i retain the value of variable a?
a=[{'a':1,},{'b':2,}] b = a b.pop(0)
You must copy the list pointed to by 'a' if you want to retain it's value:
>>> a=[{'a':1,},{'b':2,}]
>>> b = list(a)
>>> b.pop(0)
{'a': 1}
>>> b
[{'b': 2}]
>>> a
[{'a': 1}, {'b': 2}]
If you write b=a
, the two names a and b refer to the same instance of list.
To retain the value you should prepare copy of the list, if deep copy is not needed, you can do it with slicing (otherwise use copy module)
>>> a=[{'a':1,},{'b':2,}]
>>> b = a
>>> b.pop(0)
{'a': 1}
>>> a
[{'b': 2}]
>>> b
[{'b': 2}]
>>> a=[{'a':1,},{'b':2,}]
>>> b=a[:]
>>> b.pop(0)
{'a': 1}
>>> a
[{'a': 1}, {'b': 2}]
>>> b
[{'b': 2}]
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.