You need to read about mutable and immutable objects in Python.
Dictionaries are mutable objects, so they could be changed in-place:
internally, a new python object is created. You can check it with
ids will be different...
Dictionaries are mutable objects, so they could be changed in-place:
single_alien = {'color': 'grey', 'points': 8, 'speed': 'ultraslow'} print(id(single_alien)) # print unique identifier of the object single_alien # assume, that returned by `id` value is 12345 single_alien['color'] = 'green' single_alien['points'] = 5 single_alien['speed'] = 'slow' print(id(single_alien)) # lets print id again, after changes... # it is 12345! # So, the object was changed in-place, this is mutability... aliens.append(single_alien) single_alien['color'] = 'blue' single_alien['points'] = 6 single_alien['speed'] = 'medium' print(id(single_alien)) # it is still... 12345! aliens.append(single_alien)So, each time you appending single_alien to aliens, Python just duplicates references to the object single_alien;
for alien in aliens: print(id(alien)) # will give the same valuesEach time you assigning a new dictionary to the single_alien,
internally, a new python object is created. You can check it with
id
.ids will be different...
single_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} print(id(single_alien)) # eg. 123456 aliens.append(single_alien) single_alien = {'color': 'blue', 'points': 6, 'speed': 'medium'} print(id(single_alien)) # eg. 123234 123234!=123456, i.e. another object! aliens.append(single_alien)