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

--

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)

--

--

Python: iter, enumerate, zip

3 min read

Oct 9

Python: Exception Handling

3 min read

Oct 9

Python: remove() and pop()

3 min read

Oct 6

Python: update() method of dictionary

2 min read

Apr 16

Tail recusion and tail recursive elimination

2 min read

Apr 10

Python -1

1 min read

Apr 1

Python: Local, Nonlocal and Global variables

2 min read

Sep 27

Python: GIL (Global Interpreter Lock)

2 min read

Sep 27

Python: Deep and Shallow Copy

2 min read

Sep 25

Python: range(), numpy.arange(), and numpy.linspace()

3 min read

Sep 9

Rahul S

I learn as I write | LLM, NLP, Statistics, ML