Random Module In Python

Aug 27th, 2021 - written by Kimserey with .

The random module in Python provides a way to generate pseudo-random numbers for various distributions. In this post, we will explore the most commmonly used functionalities of the random module; generating random integers and selecting randomly from sequences.

Generating Random Integers

For generating random integers we can use randrage(start, stop[, step]). It will generate a random integeter between start and stop excluded. An optional step can be added to generate random values in step. If the start value isn’t provided the default value is 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> from random import randrange

>>> randrange(10)
>>> 4

>>> randrange(5, 10)
>>> 8

>>> randrange(-10, 10)
>>> -4

>>> randrange(-10, 10, 3)
>>> 5


We can see that using randrange, we can get a random integer within the range given.

If we need a decimal value between 0 and 1, we can use the random function:

1
2
3
4
>>> from random import random

>>> random()
>>> 0.059563900839753714


And lastly if we want to get random bits, we can use the getrandbits function:

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> from random import getrandbits

>>> getrandbits(3)
>>> 2

>>> getrandbits(3)
>>> 4

>>> bin(getrandbits(3))
>>> '0b111'

>>> bin(getrandbits(3))
>>> '0b11'


getrandbits actually generates an integer, but the integer is guaranteed to be of k bits as we can see in the example.

Selecting Randomly From Sequences

Using the random module, we can also select random values out of a sequence with choice:

1
2
3
4
5
6
7
8
9
>>> from random import choice

>>> a = [1, 2, 3, 4]

>>> choice(a)
>>> 3

>>> choice(a)
>>> 2


choice accepts a sequence as parameter and will randomly output one value from the sequence.

Lastly choices provides us a way to get k random elements from a sequence with replacement. With replacement simply means that at each pick, every value have the same probability to be picked as they have on previous picks.

1
2
3
4
5
6
7
>>> a = [1, 2, 3, 4]

>>> choices(a, k=2)
>>> [4, 2]

>>> choices(a, k=2)
>>> [3, 3]


Here we asked to get two elements chosen randomly from a. We can see that it’s possible to get 3, 3 as the selection is done with replacement.

choices also accepts either relative weights or cumulative weights which can be use to add weight to the selection:

1
2
>>> choices(a, weights=[100, 1, 2, 3], k=3)
>>> [1, 1, 1]


Setting a relative weight of 100 on the first element of a will skew heavily the pick which we then see return only 1s.

Conclusion

And that concludes today’s post on random module! In this post, I’ve only covered the 10% functionalities of random which I use all the time, but for the rest feel free to checkout the official documentation linked below. I hope you liked this post and I see you on the next one!

External Sources

Designed, built and maintained by Kimserey Lam.