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
Python Random choice() Method The choice() method returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple or any other kind of sequence.
The fundamental difference is that random. choices() will (eventually) draw elements at the same position (always sample from the entire sequence, so, once drawn, the elements are replaced - with replacement), while random.
random. choice() accepts one argument: the list from which you want to select an item. You may encounter a scenario where you want to choose an item randomly from a list.
Indeed, whenever we call a python function, such as np. random. rand() the output can only be deterministic and cannot be truly random. Hence, numpy has to come up with a trick to generate sequences of numbers that look like random and behave as if they came from a purely random source, and this is what PRNG are.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With