List of dictionaries created by loop - problem to change value

1989 views python

I created list of dictionaries using loop like this:

some_dict = {'Color': 'Red'}
list_of_dict = []
n = 3

for i in range(n):

But when I want now change value of the first dictionary it changes this value in each dictionary of the list.

list_of_dict[0]['Color'] = 'Blue'

Expected output is:

[{'Color': 'Blue'}, {'Color': 'Red'}, {'Color': 'Red'}]

But what I actually get is that:

[{'Color': 'Blue'}, {'Color': 'Blue'}, {'Color': 'Blue'}]

Please help me if you can.

answered question

To the downvoter: You might be bit harsh. This is a post by a new user with a Minimal, Complete, and Verifiable example. Everything is runnable and we have input, expected output and actual output.

1 Answer


Appending to a list does not copy any data - you are appending literally the same object in memory three times to your list.

However, your code can be easily fixed by using


in the loop's body.

See How to copy a dictionary and only edit the copy for more information.

posted this

Have an answer?


Please login first before posting an answer.