5

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.

mahifoo
  • 51
  • 3
  • 2
    You can use `random.sample()`. See this [link](http://stackoverflow.com/questions/22842289/python-generate-n-unique-random-numbers-within-a-range) – Amal Rajan Jul 29 '16 at 10:15
  • It's a bit annoying when the question gets closed whilst you're coding a solution. I've posted an answer here if you still need it: https://repl.it/ChS5 – logic-unit Jul 29 '16 at 10:27

3 Answers3

2

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

Lynn
  • 10,425
  • 43
  • 75
1

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)
...
L3viathan
  • 26,748
  • 2
  • 58
  • 81
0

Create a generator that checks from previous generated choice:

import random
def randomNotPrevious(l):
    prev = None
    while True:
        choice =  random.choice(l)
        if choice != prev:
            prev = choice
            yield choice

>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> randomLst = randomNotPrevious(l)
>>> next(randomLst)
1
>>> next(randomLst)
5
>>> next(randomLst)
3
>>> next(randomLst)
6
>>> next(randomLst)
5
Netwave
  • 40,134
  • 6
  • 50
  • 93