# Python. Extract random object from a list

6

The problem is that I have a list `"l"` of which I want to select a random item several times without repeating it, and I do not know how to do it. Any suggestions?

``````import random

l = ["a", "b", "c", "d"]

sel1 = random.choice(l)
``````

That's fine, but now I want to define a `"sel2"` that is a random element of `"l"` but different of `"sel1"` . And so we can continue defining a `"sel3"` different from `"sel1"` and `"sel2"` .

asked by 256 20.06.2016 в 01:54
source

3

Instead of randomly choosing element by element, make a random arrangement of the entire list:

``````l2 = l[:]  # copia de la lista
random.shuffle(l2)

sel1, sel2, sel3 = l2[:3]
``````

or more simple, use `random.sample` :

``````sel1, sel2, sel3 = random.sample(l, 3)
``````

2

You could give another approach to your problem: why not mess up the list and take each element out of it?

The `shuffle` function allows you to clutter the elements in a list. Look at this example:

``````from random import shuffle

list = ["a", "b", "c", "d"]
shuffle(list) # list -> ["c", "a", "d", "b"]

sel1 = list[0] # "c"
sel2 = list[1] # "a"
....
``````

Greetings.

0

You can try this little function:

``````import random
def random_sin_repetir(lista):
for _ in range(0,len(lista)):
result = random.choice(lista)
yield result
lista.remove(result)
``````

You can check the results with:

``````lista = ["a", "b", "c", "d"]
[i for i in random_sin_repetir(lista)]
``````

['a', 'c', 'b', 'd']

``````lista = ["a", "b", "c", "d"]
[i for i in random_sin_repetir(lista)]
``````

['b', 'd', 'c', 'a']

``````lista_original = list(set(lista_original))