# How to select some random elements from a list in python

I have a list and want to select some random elements from the list. I can write the code for this, but is there any built-in function in python to select random elements?

E.g. a=[1,2,3,4,5,6,7,8,9,10] and I want to select 4 elements randomly. i.e. aa=[5,8,1,9]

by (19k points)

You can use the random module for this task. There may be several ways, I know the following 3 ways to do this task.

Approach 1

>>> bb=[1,2,3,4,5,6,7,8,9,10,11,12,13,14]

>>> import random

>>> random.sample(bb,5)

[2, 10, 1, 13, 6]

Approach 2

>>> from numpy import random

>>> random.choice(bb,5)

array([ 4,  2, 14,  1,  6])

Approach 3

>>> random.shuffle(bb)

>>> bb

[9, 11, 1, 13, 4, 5, 3, 12, 14, 10, 2, 7, 8, 6]

>>> bb[:5]

[9, 11, 1, 13, 4]

by (11.5k points)
numpy.random.choice does not give unique indices. It sometimes repeats. So, if you want unique indices, go with approach 1 or approach 3. Have a look at the following example:

>>> b=np.array([1,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1])
>>> f=np.where(b==1)[0]
>>> f
array([ 0,  4,  5,  6,  9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 30, 33, 34],
dtype=int64)
>>> np.random.choice(f,10)
array([16, 33, 29,  4, 11, 34, 17, 10, 18,  9], dtype=int64)
>>> np.random.choice(f,12)
array([13, 13, 10,  4, 33, 33,  9, 18, 14, 17, 17,  4], dtype=int64)