Why this little change in code make this code works differently. I'm just learning Python. Can anyone explain in simple way? Edit: I didn't realized that appending dictionary in to list is pointing to the same dictionary and not making actual copy of it. I was trying to find solution here before this post but probably formulating my problem was tad different and it might cause for experienced programmers viewing it as duplicate.
Input
# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
# Show the first 5 aliens:
for alien in aliens[:5]:
print(alien)
print("...")
# Show how many aliens have been created.
print("Total number of aliens: " + str(len(aliens)))
OUTPUT
{'points': 10, 'color': 'yellow', 'speed': 'medium'}
{'points': 10, 'color': 'yellow', 'speed': 'medium'}
{'points': 10, 'color': 'yellow', 'speed': 'medium'}
{'points': 5, 'color': 'green', 'speed': 'slow'}
{'points': 5, 'color': 'green', 'speed': 'slow'}
...
Total number of aliens: 30
Now changed the code I'll initialize dictionary outside the first for loop
Input
# Make an empty list for storing aliens.
aliens = []
# HERE IS THE CHANGE
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
# Make 30 green aliens.
for alien_number in range(30):
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
# Show the first 5 aliens:
for alien in aliens[:5]:
print(alien)
print("...")
# Show how many aliens have been created.
print("Total number of aliens: " + str(len(aliens)))
Output
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
...
Total number of aliens: 30
Why in second is the whole dictionary changed and not just first 3 dictionaories?