-1

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]
okuoub
  • 716
  • 6
  • 19
  • 52

5 Answers5

2

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]
Sunitha
  • 11,422
  • 2
  • 17
  • 22
  • Almost... `randint()` *includes* the end number so if `len(l)` is chosen - it'll be an invalid index and cause an `IndexError` on the pop attempt... you want `random.randrange(len(l))` – Jon Clements Aug 19 '18 at 10:53
  • ha... thanks for the explanation.. Updated the answer – Sunitha Aug 19 '18 at 11:28
  • I suppose you can do that... but `randint` calls `randrange(a, b+1)` so you might as well just call `randrange` directly :) – Jon Clements Aug 19 '18 at 11:30
0

You can try this: l.pop(random.randint(0, len(l)))

p.s. sorry, forgot about random

ImZ
  • 46
  • 1
  • 9
0

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]
Austin
  • 25,142
  • 4
  • 21
  • 46
0

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)
Black Thunder
  • 6,215
  • 5
  • 27
  • 56
0

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.
Kaushik NP
  • 6,446
  • 8
  • 30
  • 57