0

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'}
  • The problem is the same as in the dupe. You have _one_ objectreference if you create it outside the loop and add the _same_ object 30times. All references point to the same data. (its the same for list and dicts). You change the data through one reference and all point still to the same changed data. – Patrick Artner Jun 13 '19 at 15:56
  • oh i see, makes perfect sense now. Thanks! – Mohammed Osama Jun 13 '19 at 15:58

1 Answers1

1

First case: you're creating a new object in the loop each time. Each member of aliens is distinct.

Second case: the same object is inserted in the list 30 times. It's 30 references to the same object in the list aliens. If you change the object with 1 reference, all the other references reflect that change.

rdas
  • 20,604
  • 6
  • 33
  • 46
  • Oh that is a great point! So its as if I am changing everything at the same time because i have repeated ```new_alien``` 30 times in the the list. Thanks for the great and quick response! – Mohammed Osama Jun 13 '19 at 15:56