Reputation: 35
Anyone know why when I run this code I get the same dictionary entry appended 100 times?
from random import choice
aliens = []
alien = {}
colors = ['red', 'blue', 'green', 'black', 'purple', 'brown', 'yellow', 'coral']
points = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
speeds = ['slow', 'medium', 'fast']
for i in range(1,101):
alien['color'] = choice(colors)
alien['points'] = choice(points)
alien['speed'] = choice(speeds)
aliens.append(alien)
print(aliens)
Upvotes: 0
Views: 237
Reputation: 189
The dictionary as well as the list is stored by the link and adding it to another list, you simply create a new link to the same dictionary. Just use alien.copy()
.
from random import choice
aliens = []
alien = {}
colors = ['red', 'blue', 'green', 'black', 'purple', 'brown', 'yellow', 'coral']
points = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
speeds = ['slow', 'medium', 'fast']
for i in range(1,101):
alien['color'] = choice(colors)
alien['points'] = choice(points)
alien['speed'] = choice(speeds)
aliens.append(alien.copy())
print(aliens)
Upvotes: 2