So I have a list with integers like this:
list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
And I want to choose random integer from it with choice:
item = random.choice(list)
But how do I make sure the next time I do this, it is different item? I don't want to remove items from my list.
If you want n different random values from a list, use random.sample(list, n)
.
If you need them all anyways and just want them in a random order (but you don't want to change your list), or if you don't have an upper bound on how many items you want to sample (apart from the list size):
import random
def random_order(some_list):
order = list(range(len(some_list)))
random.shuffle(order)
for i in order:
yield some_list[i]
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for item in random_order(my_list):
... # do stuff
Alternatively, you can use it like this:
order = random_order(my_list)
some_item = next(order)
some_item = next(order)
...
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