Is there a single command to randomly sample an item for a list and remove it? let say the command named cmd, I want something like that?
l = [1,2,4,6]
r = cmd(l)
r = 4
l = [1,2,6]
Is there a single command to randomly sample an item for a list and remove it? let say the command named cmd, I want something like that?
l = [1,2,4,6]
r = cmd(l)
r = 4
l = [1,2,6]
Use random.randint
to get a random index and use pop
to get the element with that index from the list
>>> import random
>>> l = [1,2,4,6]
>>> idx = random.randint(0, len(l)-1)
>>> r = l.pop(idx)
>>> r
4
>>> l
[1, 2, 6]
Shuffle using random.shuffle
and then pop
from list:
import random
lst = [1, 2, 4, 6]
random.shuffle(lst)
r = lst.pop()
print(r) # 4
print(lst) # [1, 2, 6]
Use the function choice
from the module random
and use remove
to remove the item from list.
>>> from random import choice as get
>>> l = [1,2,3,4,6]
>>> r = get(l)
>>> r
3
>>> l.remove(r)
>>> l
[1, 2, 4, 6]
In short:
from random import choice as get
l = [1,2,3,4,6]
r = get(l)
l.remove(r)
The easiest way I can think of is to use shuffle()
to randomise the elements position in the list and then use pop()
as and when required.
>>> from random import shuffle
>>> shuffle(l)
>>> l.pop()
#driver values :
IN : l = [1,2,4,6]
OUT : 4
From PyDocs :
random.shuffle(x[, random])
Shuffle the sequence x in place.