Reputation: 149
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]?
Upvotes: 0
Views: 935
Reputation: 21
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]
Upvotes: 0
Reputation: 20336
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)
Upvotes: 0
Reputation: 55469
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)
Upvotes: 0
Reputation: 39223
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)]
Upvotes: 2
Reputation: 9610
import numpy
lst = [1,2,3,4]
choices = numpy.random.choice(lst, size=5, replace=True)
Upvotes: 0