I'm self-studying Python using "Python Crash Course", and have been programming most of the code in the book as well as the set questions. There is one example where a list of dictionaries is created, using this code:
# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range (0,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[0:5]:
print(alien)
print("...")
This works as expected, producing an initial list of 30 green aliens, and then the first three are modified to be yellow.
However, I was experimenting with the code, and I wondered why the
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
line was inside the first for loop (as it seemed to be creating the same thing every time, it seemed redundant to me that it was inside the loop).
Moving it outside (I'll only put the relevant changes, so the second block of code is altered):
# Make 30 green aliens.
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
for alien_number in range (0,30):
aliens.append(new_alien)
This produces output that I can't understand - ALL the aliens become yellow - the [0:3] part of the second for loop has no effect - I tried setting it to all sorts of values, and none of the changed the function - they all and up being altered by the second loop.
Could someone explain why this is happening? I'm happy to read an appropriate link if someone can provide one, but I can't think of what to search for that would explain this (as I don't know what's happening, therefore don't know what to look for other than Yellow Aliens!)