-2

I have one dictionary:

dog = {'color': 'black'}

I created 3 similar dogs inside one list:

dogs = []
dog = {'color': 'black'}
for num in range(3):
   dogs.append(dog)

When I try to modify first dog of my dogs list:

dogs[0]['color'] = 'white'

It retrieves me whole list been modified:

[{'color': 'white'}, {'color': 'white'}, {'color': 'white'}]

But when I declare my dog dictionary inside for loop and try to change single dog dictionary:

for num in range(3):
 dog = {'color': 'black'}
 dogs.append (dog)

 dogs[0]['color'] = 'white'

I get the desired output:

[{'color': 'white'}, {'color': 'black'}, {'color': 'black'}]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ojacomarket
  • 493
  • 2
  • 7

2 Answers2

0

In your first example, you are always appending the same object/same dog.

In the second example, you are appending three different objects, as you are creating them in the loop.

If you'd like to append copies of your dog, just do:

dogs = []
dog = {'color': 'black'}
for num in range(3):
   dogs.append(dog.copy())

Be aware that in this case, the original dog is not a part of your dogs list, only copies of it.

edit: if your dict is nested, you'll need .deepcopy() --> https://stackoverflow.com/a/2465951/13450078

0

The difference is that in the first example

dogs = []
dog = {'color': 'black'}
for num in range(3):
   dogs.append(dog)
dogs[0]['color'] = 'white'

each dog in the dogs list refer to the same dog dictionary and by changing the color of the dictionary it's reflecting on the same object.
In the second code

for num in range(3):
    dog = {'color': 'black'}
    dogs.append (dog)

dogs[0]['color'] = 'white'

On each iteration, a new dictionary object is created so by adding each object to the list the reference of the list item to a dictionary object is different and by that, if you are changing the color of a specific item from the list it's changing only his value.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17