-1
test = [{}]*5 # Creates [{}, {}, {}, {}, {}]
print(test[1]) # outputs "{}"

test[1]['asdf'] = 5

print(test)

This gives test as [{'asdf': 5}, {'asdf': 5}, {'asdf': 5}, {'asdf': 5}, {'asdf': 5}]. Somehow, all the dictionaries in the list have been set to the same value

But this doesn't happen if we initialize the list a different way:

test2 = [{} for i in range(5)] # Also [{}, {}, {}, {}, {}]
test2[1]['asdf'] = 1

print(test2) 

test2 now equals [{}, {'asdf': 1}, {}, {}, {}], the expected result.

James Wright
  • 1,293
  • 2
  • 16
  • 32

1 Answers1

0

The difference between the two is that for [{}]*5, Python creates a 5 element list containing the dictionary given in the square brackets. Ie. it's 5 different references to the same dictionary.

While the other method creates a new dictionary for every element in the list.

More detailed explanation can be found in the duplicate question link

James Wright
  • 1,293
  • 2
  • 16
  • 32