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

--

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 or set.

  • Returns a new list containing elements from the population while leaving the original population unchanged.
  • To choose a sample from a range of integers, use range() for the population argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60)
import random 
random_sample = random.sample(population, k)

randrange():Generating a random integer from a range with a specified step.

import random 
random_num = random.randrange(start, stop, step)

seed()Setting a seed value to ensure reproducibility of random results.

import random 
random.seed(seed_value)

random.seed()(Module-Level Seed): Setting the seed value for the entire random module.

import random 
random.seed(seed_value)

--

--