0

I just spent an hour with the following frustration, and

a) wanted to post it in case someone else has the same problem, and b) i am very curious what underlies this behavior.

$ e = [{}]*6
$ e
[{}, {}, {}, {}, {}, {}]
$ e[0]['green'] = 'blue'
$ e
[{'green': 'blue'}, {'green': 'blue'}, {'green': 'blue'}, {'green': 'blue'}, {'green': 'blue'}, {'green': 'blue'}]
$ e = [{}, {}, {}, {}, {}, {}]
$ e
[{}, {}, {}, {}, {}, {}]
$ e[0]['green'] = 'blue'
$ e
[{'green': 'blue'}, {}, {}, {}, {}, {}]

Basically, the problem is when a list of dictionaries is initialized with [{}]*int, attempts to modify a single dictionary by its index in the list modifies all dictionaries. Whereas explicitly initializ

Thanks

2 Answers2

4

because you are putting same dict 6 times. [{}]*6 wouldn't copy/deepcopy the original dict but only the reference to it. If you want 6 separate dict use a loop/list comprehension e.g

e = [{} for i in range(6)] 

See more explanation in python doc

Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
  • That's right! To elaborate, when you do `[X] * N` in Python, all you are saying is *give me N references to X in a list* (where X can be any mutable type). They all end up pointing to the same thing and changing any one of them ends up changing all of them. – ktdrv Apr 26 '12 at 21:16
1

The answer is: mutability. And it is not strange.

In first case:

>>> e = [{}]*6

you create a list from one dictionary repeated 6 times. If you change one of the elements, you change the other elements (at least it looks like, because in fact these "other" elements are the same element).

In the second case:

>>> e = [{}, {}, {}, {}, {}, {}]

you created a list from 6 different dictionaries, so changing one does not influence the others.

Tadeck
  • 132,510
  • 28
  • 152
  • 198