Quick one on Python random numbers sampling

I have been working on a project to generate random data using Python. Since I am not using this project for any security application I opted for the Python pseudo-random number generator random .

In order to randomly select items from a list three option presented themselves to me random.choice, random.choices and random.sample .


Selects one item randomly from list of length n.

>>> import random
>>> random.choice([4,2,6,7,1])
>>> random.choice([4,2,6,7,1])


Selects k items randomly from list of length n.

>>> import random
>>> random.choices([4,2,6,7,1],k=2)
[2, 6]
>>> random.choices([4,2,6,7,1],k=20)
[6, 4, 1, 6, 1, 1, 6, 7, 7, 2, 4, 4, 2, 2, 6, 1, 4, 6, 7, 4]


Select k items randomly from list of length n, without replacement. Randomly select items are removed from the list, therefore if k > n there is an error.

>>> import random
>>> random.sample([4,2,6,7,1],k=3)
[6, 4, 1]
>>> random.sample([4,2,6,7,1],k=20)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/random.py", line 363, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative

Hopefully , I have given a concise introduction random item selection from a list in Python. Refer to the documentation for more functions and information.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.