0

I needed to create a list of None objects and used this form

a = [None] *2
a[0] = 0

the value of a was:

[1, None]

however, when i tried the same thing with:

a = [{'elem' : 0}] * 2

and after that

a[1]['elem'] = 0

the value of a became:

[{'elem': 1}, {'elem': 1}]

can anyone help me understand the mechanism behind this?

user1262882
  • 79
  • 1
  • 3

2 Answers2

1
a = [{'elem' : 0}] * 2

'a' contains two references to the same dictionary. The equivalent of the first case would be:

a[0] = {'elem' : 1}
amsh
  • 210
  • 6
  • 15
0

By using multiplication, you created list of references to the same dictionary

In [11]: a = [{'elem' : 0}] * 2
In [14]: for elem in a:
    print id(elem)
   ....:     
142676420
142676420

To create list of 2 independent dictionaries

In [15]: a = [{'elem' : 0} for _ in range(2)]

In [16]: for elem in a:
    print id(elem)
   ....:     
142695116
142695932
volcano
  • 3,578
  • 21
  • 28