Steve S
Steve S

Reputation: 35

Python Random Choice Returning Same Result in Every Loop Iteration

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

Answers (1)

Ruslan
Ruslan

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

Related Questions