107

I tried the following in the python interpreter:

>>> a = []
>>> b = {1:'one'}
>>> a.append(b)
>>> a
[{1: 'one'}]
>>> b[1] = 'ONE'
>>> a
[{1: 'ONE'}]

Here, after appending the dictionary b to the list a, I'm changing the value corresponding to the key 1 in dictionary b. Somehow this change gets reflected in the list too. When I append a dictionary to a list, am I not just appending the value of dictionary? It looks as if I have appended a pointer to the dictionary to the list and hence the changes to the dictionary are getting reflected in the list too.

I do not want the change to get reflected in the list. How do I do it?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
neo29
  • 1,073
  • 2
  • 8
  • 4
  • Chekhov You should also see this question: (http://stackoverflow.com/questions/5242933/why-in-python-list-elem-modifies-the-original-list) – eyquem Mar 09 '11 at 11:38
  • This is essentially a duplicate of [List changes unexpectedly after assignment](/q/2612802/4518341) except that the object is a dict and the reference is an element of a list, not a name. – wjandrea Mar 30 '22 at 01:40

3 Answers3

165

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
40

Also with dict

a = []
b = {1:'one'}

a.append(dict(b))
print a
b[1]='iuqsdgf'
print a

result

[{1: 'one'}]
[{1: 'one'}]
eyquem
  • 26,771
  • 7
  • 38
  • 46
  • Not sure if it's fast enough as copy(), but seems to be faster than deepcopy(). Maybe with complicated dictionary schema it'll be close to deepcopy() because dict() creates a new dictionary. – selotec May 30 '16 at 09:55
  • @selotec To be clear, this is a shallow copy, not a deep copy. – wjandrea Mar 30 '22 at 01:37
3

use copy and deep copy

http://docs.python.org/library/copy.html

Mohammad Efazati
  • 4,812
  • 2
  • 35
  • 50