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)
3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by pyTony
1

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.

Edited by Gribouillis: n/a

Attachments list.png 2.96 KB
0

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}]
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.