-1

I have a list with empty dictionaries. If I update one element of the list, I see same changes in all other elements as well.

my_list = [{}] * 5
print(my_list)
my_list[0]["name"] = "john"
print(my_list)

Outputs:

[{}, {}, {}, {}, {}]
[{'name': 'john'}, {'name': 'john'}, {'name': 'john'}, {'name': 'john'}, {'name': 'john'}]

I expected an output like this:

[{}, {}, {}, {}, {}]
[{'name': 'john'}, {}, {}, {}, {}]

Any suggestions will be appreciated.

SadHak
  • 367
  • 1
  • 2
  • 9
  • ^ it doesn't matter that the above is about lists, the principle is the same – roganjosh Jul 26 '20 at 22:13
  • 2
    `[{}] * 5` That creates five identical references to the same dict object. Updating one of them updates all of them, because they're _the same object_. – John Gordon Jul 26 '20 at 22:13

1 Answers1

1

It creates a list of references to the same dictionary. Try using something like this : my_list = [dict() for x in range(n)] where n is the number of ducts you want

Diana
  • 140
  • 5
  • 2
    Please do not answer questions that should not have been asked, or have a clear duplicate already on the site. – Prune Jul 26 '20 at 22:21