When I change the location of the new_alien
dictionary to within the initial for loop, the output acts as expected. My main issue is when I change the location of new_alien
to outside the loop, the final output changes all of the list into the one in the second for loop. I am kinda new to dictionaries so I appreciate the help!
#example code from Python Crash Course by Eric Matthes that i used as practice
aliens = []
#the problematic dictionary location
#new_alien = {'color' : 'green', 'points' : 5, 'speed' : 'slow'}
for number in range(0,30):
new_alien = {'color' : 'green', 'points' : 5, 'speed' : 'slow'}
aliens.append(new_alien)
for change in aliens[0:3]:
if change['color'] == 'green':
change['color'] = 'yellow'
change['points'] = 10
change['speed'] = 'medium'
for test in aliens[:5]:
print(test)
The expected result is as follows:
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
but when i change the new_alien
dictionary to before the first for loop, the result is as follows:
{'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'}