John Smith
John Smith

Reputation: 633

random.choice always same

I have a quick question. I'm currently using random.choice() to pick from a list and was wondering why it always calls the same item. It changes once I stop the program and restart it. Could anyone explain to me how the random class works and makes it so it does this?

Thanks

Upvotes: 7

Views: 19105

Answers (2)

richard
richard

Reputation: 11

Sorry its 11 years late

Incase anyone is having the same issue I had the "random.choice" command outside a while loop

Put it inside the while loop it works now

Upvotes: 1

jdi
jdi

Reputation: 92569

This is my guess as to what you are most likely doing:

import random

l = [1,2,3,4,5]
random.Random(500).choice(l)
# 4
random.Random(500).choice(l)
# 4
random.Random(500).choice(l)
# 4

If you are using the actual Random class with the same seed, and making a new instance each time, then you are performing the same pseudo random operation. This is actually a feature (seeding) to let you have a reproducible randomization in future runs of your routine.

Either do this with a seed:

l = [1,2,3,4,5]
r = random.Random(500) # seed number is arbitrary 
r.choice(l)
r.choice(l)

Or use the convenience method: random.choice(l)

Upvotes: 10

Related Questions