1

If I create a list with an empty dictionary in it, then multiply that list by a number, it seems that instead of adding more dictionaries to the list, python just populates the list with more references to the same dictionary.

>>> d = [{}]*3
>>> d[0]["x"] = 43
>>> d
[{'x': 43}, {'x': 43}, {'x': 43}]

As you can see, adding an element in one of the dictionaries leads to insertion into all of them, which means that there is in fact only one dictionary, with three pointers in d to it.

Why is this? What is the best way to add a number of empty dicts to a list in Python?

Sahand
  • 7,980
  • 23
  • 69
  • 137
  • Similarly, specific to dictionary: [Unexpected Data Assignment in Python Nested Dictionaries](https://stackoverflow.com/questions/32511394/unexpected-data-assignment-in-python-nested-dictionaries) – metatoaster May 24 '18 at 13:45
  • 2
    The two answers differ but in a single word. I wonder what's the difference between "can" and "should". <_ – bipll May 24 '18 at 13:45
  • 2
    `d = [{}]*3` creates one list with 3 pointers to it. If you change the content of one, it will also affect the others. – offeltoffel May 24 '18 at 13:45
  • 2
    @bipll They were written at the same time. For me, _should_ is a tad too strong, but I'm biased. :) – user4815162342 May 24 '18 at 13:50

2 Answers2

3

You should use a list comprehension:

d = [{} for _ in range(3)]

This creates a list of dictionaries with different pointers.

As you noticed, [{}]*3 creates a list of dictionaries with the same pointer.

jpp
  • 159,742
  • 34
  • 281
  • 339
2

You can use a list comprehension:

d = [{} for _ in range(3)]
user4815162342
  • 141,790
  • 18
  • 296
  • 355