1 min read

Python Random Module

The random module implements pseudo-random number generators for various distributions.

Warning: The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module.

Importing the Module

import random

Random Integers

# Random integer between a and b (inclusive)
print(random.randint(1, 10))

# Random integer from range(start, stop, step)
print(random.randrange(0, 101, 2)) # Even number between 0 and 100

Random Floats

# Random float between 0.0 and 1.0
print(random.random())

# Random float between a and b
print(random.uniform(1.5, 10.5))

Sequence Operations

Choice

Pick a random element from a non-empty sequence.

items = ['apple', 'banana', 'cherry']
print(random.choice(items))

Shuffle

Shuffle a sequence in place.

deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)

Sample

Return a k length list of unique elements chosen from the population.

print(random.sample(range(100), 5))

Seeding

Initialize the random number generator. Useful for reproducibility.

random.seed(42)
print(random.random()) # Will always print the same number for this seed

programming/python/python