Random selection and sampling in Python

Easy to use

Generate Random integer Please use random.randint(), for example, in the range of [0-10]:

>>> random.randint(0,10)
2
>>> random.randint(0,10)
5
>>> random.randint(0,10)
0
>>> random.randint(0,10)
7
>>> random.randint(0,10)
10
>>> random.randint(0,10)
3
>>>

To generate Floating point numbers uniformly distributed within the range of 0 to 1 Using random.random():

>>> random.random()
0.9406677561675867
>>> random.random()
0.133129581343897
>>> random.random()
0.4144991136919316
>>>

If you want to obtain N-bit random bit (Binary) integer, using random.getrandbits():

>>> random.getrandbits(200)
335837000776573622800628485064121869519521710558559406913275

If you just want to Disrupting the order of elements in a sequence random.shuffle() can be used:

>>> random.shuffle(values)
>>> values
[2, 4, 6, 5, 3, 1]
>>> random.shuffle(values)
>>> values
[3, 5, 2, 1, 6, 4]
>>>

Introduction to the differences between numpy. random. choice(), random. choice(), and random. choices() in Python

choice() in numpy

Choice() and Choices() in random

random. sample()

Other references: Introduction to the differences between numpy. random. choice(), random. choice(), and random. choices() in Python.

Related articles