Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a random integer from list, different from previous? [duplicate]

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.

like image 941
mahifoo Avatar asked Oct 19 '22 04:10

mahifoo


2 Answers

If you want n different random values from a list, use random.sample(list, n).

like image 143
Lynn Avatar answered Oct 22 '22 11:10

Lynn


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)
...
like image 33
L3viathan Avatar answered Oct 22 '22 11:10

L3viathan