0

I need to pick random elements from a list. And the number of random elements is larger than the length of the list (so I will have duplicates). Therefore I can't use random.sample(), because the sample can't be larger than the population. Does anyone have a solution?

For example:

lst = [1,2,3,4]

How can I pick 5 random elements from this list, like [1,4,3,1,2]?

Materials
  • 149
  • 1
  • 3
  • 12
  • 1
    Pick a single random element 5 times? – Scott Hunter Mar 10 '16 at 21:06
  • Use `random.choice` in a loop / list comprehension / generator expression. See http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python – PM 2Ring Mar 10 '16 at 21:07

5 Answers5

2

If I understand correctly, that you want to pick at random from a population, this should do the trick:

import random

list = [1, 2, 3, 4]

random_elements = [random.choice(list) for n in range(5)]
Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
0
import numpy
lst = [1,2,3,4]
choices = numpy.random.choice(lst, size=5, replace=True)
Alan
  • 9,410
  • 15
  • 20
0

Use random.choice in a loop or list comprehension to return random elements from your input list.

Here's a list comprehension example:

from random import choice

lst =  [10, 20, 30, 40]

num = 5
seq = [choice(lst) for _ in range(num)]
print(seq)

typical output

[20, 40, 10, 30, 20]

And here's the same thing using a "traditional for loop:

from random import choice

lst =  [10, 20, 30, 40]

num = 5
seq = []
for _ in range(num):
    seq.append(choice(lst))
print(seq)
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

You need no third-party modules. Just use a list comprehension:

choices = [random.choice(lst) for _ in range(5)]

Another way that is a little shorter, but not as efficient is this:

choices = list(map(random.choice, [lst]*5))

In Python2, map() already returns a list, so you could do:

choices = map(random.choice, [lst]*5)
zondo
  • 19,901
  • 8
  • 44
  • 83
0

My answer involves the random.choice function and a list comprehension.

I suggest also to put the magic inside a function whose name makes explicit what it does.

import random

def pick_n_samples_from_list(n, l):
    return [random.choice(l) for n in range(n)]

n = 5
lst = [1, 2, 3, 4]
print(pick_n_samples_from_list(n, lst))
>[3, 1, 4, 4, 1]
clement
  • 21
  • 1
  • 5