Python: random library cheatsheet

From basic random number generation to advanced techniques like Gaussian distribution, discover how Python random library adds controlled randomness to Python projects.

Rahul S
2 min readSep 10, 2023

The random library in Python provides functions and classes for generating random numbers and data.

random(): Generating a random floating-point number between 0 and 1.

random_num = random.random()

randint() : Generating a random integer within a specified range.

import random 
random_int = random.randint(start, end)

uniform(): Generating a random floating-point number within a specified range.

import random 
random_float = random.uniform(start, end)

choice():Selecting a random item from a sequence (list, tuple, string, etc.).

import random 
random_item = random.choice(sequence)

shuffle():Shuffling the elements of a list randomly. It change the list. It is an inplace operation. You cannot assign it a new variable.

import random 
random.shuffle(my_list)

sample(population,k):Chooses k unique random elements from a population sequence…

--

--