1

I was expecting below ways of initialization to result in same output:

a = [{}, {}]
b = [{}] * 2
a[0]["assigned"] = 1
b[0]["assigned"] = 1
print(a)
print(b)

but the output is as follows:

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

Looks like in case of b, a single dictionary instance is being created and referenced in all the list elements.

Can someone help me with reason behind this implementation?

Thanks.

Sociopath
  • 13,068
  • 19
  • 47
  • 75
bmc
  • 51
  • 4

1 Answers1

1

Multiplying a list evidently copies references to objects. As it can be seen here:

>>> obj = object()
>>> id(obj)
140589987770544
>>> 
>>> objects = [obj] * 5
>>> print(*map(id, objects), sep="\n")
140589987770544
140589987770544
140589987770544
140589987770544
140589987770544

The fix for this is to create a new object in a list comprehension:

>>> objects = [object() for _ in range(5)]
>>> print(*map(id, objects), sep="\n")
140589987770576
140589987770528
140589987770560
140589987770592
140589987770608
Goodies
  • 4,439
  • 3
  • 31
  • 57