I noticed something odd while helping a collegue with his Python 2.7 script. He has a dictionary with lists as the dictionary values. He was assigning the dictionary values to a new variable and then performing some edits to the list. The odd part that got me was the list changes in the new variable were also being reflected in the dictionary. I repeated a simple example in the shell and I posted it below. I also tried the same thing but with a string as the dictionary value, but to no effect. Is there something I am missing here or is this some sort of bug? Thanks.
>>> dict1 = {}
>>> dict1['foo'] = [1,2,3]
>>> print dict1
{'foo': [1, 2, 3]}
>>> bar = dict1['foo']
>>> bar.append(4)
>>> print dict1
{'foo': [1, 2, 3, 4]}
In the example above I would have expected the 4 to be appended to bar and the value of ‘foo’ to remain [1,2,3].
You don’t get a copy of the list, you get a reference to the list itself. Since lists are mutable, the behaviour is entirely expected.
Compare this to using a second variable pointing to a list:
If you wanted to have an independent list instead, make a copy:
Another way to make a copy is to use the full-list slice: