Random Module

The random module generates pseudo-random numbers and makes random selections, which is useful for simulations, sampling data, shuffling datasets, and testing.

Generating Random Numbers

import random

print(random.random())          # random float between 0.0 and 1.0
print(random.randint(1, 100))   # random integer between 1 and 100 (inclusive)
print(random.uniform(1, 10))    # random float between 1 and 10

Random Selection from a Sequence

import random

colors = ["red", "green", "blue", "yellow"]

print(random.choice(colors))          # pick one random item
print(random.sample(colors, 2))       # pick 2 unique random items
random.shuffle(colors)                # shuffle the list in place
print(colors)

Setting a Seed for Reproducibility

Setting a seed makes random results reproducible, which is critical in data science when you need consistent, repeatable results across multiple runs, such as when splitting data for a Machine Learning model.

random.seed(42)
print(random.randint(1, 100))   # will always produce the same value when seed is 42
In real Machine Learning workflows, setting a random seed (often via NumPy or Scikit-learn's random_state parameter) is standard practice, ensuring that experiments and results can be reliably reproduced by you or your teammates.

Coming Up Next

Next, you'll learn the json module - essential for working with data exchanged with web APIs.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course