I am currently following "Python Crash Course" by Eric Matthes.
I am adding 30 new items to a list using a for loop. All the items are dictionaries. Then I am trying to update first few items of the list using the following code (actual code posted in the end)-
for item in items[0:3]:
if item['someKey'] == 'someValue':
item['someKey'] = 'someOtherValue'
item['someOtherKey'] = 'someDifferentValue'
So, as I am changing only first 3 items, it should change only first 3 items. But it is changing all items in the list if I append to the list using variable declared outside the for loop while adding items in the first place.
#Case-1
items = []
dictionary = {'someKey': 'someValue', 'someOtherKey': 'someOtherValue'}
for item in range(30):
items.append(dictionary)
If I run this code and later run the for loop to update some items, then all items in the list get modified. The slicing of the list with [0:3]
does not work!
#Case-2
items = []
for item in range(30):
dictionary = {'someKey': 'someValue', 'someOtherKey': 'someOtherValue'}
items.append(dictionary)
So, in this case the update process works as expected. The for loop just updates only the first 3 items. Why does this happen? I have no idea! The list gets created in both the cases just fine. Only while modifying the already created list, the behaviour is differing.
Here's the actual code-
#Case-1
aliens = []
newAlien = {'color': 'green', 'speed': 'slow', 'points': 5}
for alienNumber in range(30):
aliens.append(newAlien)
print(aliens) #Prints the whole list, showing adding dicts went just fine
for alien in aliens[0:3]: #intending change for only first 3 items
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[0:5]:
print(alien) #Shows all five items are modified even though intended for first 3
Here's where this went good-
#Case-2
aliens = []
for alienNumber in range(30):
newAlien = {'color': 'green', 'speed': 'slow', 'points': 5}
aliens.append(newAlien)
print(aliens) #prints whole list, 30 dicts are added
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[0:5]:
print(alien) #Here only first 3 items are modified, as intended
Help me understand the behaviour of the the for
loop here. The loop is only supposed to add items and nothing else. How declaring the new dictionary outside the for loop changes how items are modified later?