python dictionary inside/outside for loop

SlowSloth

I would like to change one of my elements in the dictionary but if I were to put new_alien outside the loop, all the elements in the dictionary gets changed. Why is that?

#ALL aliens get changed when I put put the dictionary up here
new_alien = {'colour': 'green'}

aliens=[]

for alien_number in range(3):
    #if i put new_alien here only one alien dictionary gets changed in the for loop (correct code)
    #new_alien = {'colour': 'green'}
    aliens.append(new_alien)

print(aliens)

for alien in aliens[0:1]:
    if (alien['colour'] == 'green'):
        alien['colour'] = 'yellow'

print(aliens[0:2])

Output if new_alien is outside the loop:

[{'colour': 'green'}, {'colour': 'green'}, {'colour': 'green'}]
[{'colour': 'yellow'}, {'colour': 'yellow'}]

Output if new_alien is inside the loop:

[{'colour': 'green'}, {'colour': 'green'}, {'colour': 'green'}]
[{'colour': 'yellow'}, {'colour': 'green'}]

Notice how outside the loop ALL alien dictionary:colour gets changed to yellow. Any explanation would be appreciated. Thanks!

RoadRunner

If you put new_alien on the outside, you are appending the same object over and over again. You can print out the objects identity with id() to see what I mean here:

new_alien inside the loop:

for alien_number in range(3): 
    new_alien = {'colour': 'green', 'points': 5, 'speed': 'slow'}
    print(id(new_alien))
    aliens.append(new_alien)

Which outputs different object identities:

1577811864456
1577811864528
1577811864960

Therefore you are appending a different object every time. Different references to new_alien, 3 separate objects. If you change one object, only one object gets changed here. This is the correct way to do this.

new_alien outside the loop:

new_alien = {'colour': 'green', 'points': 5, 'speed': 'slow'}

for alien_number in range(3):
    print(id(new_alien))
    aliens.append(new_alien)

You get the same identities:

2763267730312
2763267730312
2763267730312

Which means you are appending the same object over and over again. This means that if you change one object, all of the objects will change. This is because they are all references to one object. Not the way to go if you want to modify them in the future.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related