Python Random Module

basic
Published

December 14, 2024

Python’s built-in random module is a powerful tool for generating pseudo-random numbers and making your programs more dynamic and unpredictable. Whether you’re simulating events, shuffling data, or creating games, understanding this module is essential. This post explores its core functionalities with clear code examples.

Generating Random Numbers

The most fundamental function is random(), which returns a random float between 0.0 (inclusive) and 1.0 (exclusive):

import random

random_float = random.random()
print(f"Random float: {random_float}")

Need a random integer within a specific range? Use randint():

random_integer = random.randint(1, 10)  # Generates a random integer between 1 and 10 (inclusive)
print(f"Random integer: {random_integer}")

For a random integer from a range excluding the upper bound, employ randrange():

random_integer_range = random.randrange(1, 10) # Generates a random integer between 1 and 9 (exclusive of 10)
print(f"Random integer (randrange): {random_integer_range}")

You can also generate random numbers from a given sequence using choice():

my_list = ["apple", "banana", "cherry"]
random_choice = random.choice(my_list)
print(f"Random choice: {random_choice}")

Shuffling and Sampling

The random module also provides functions for manipulating sequences:

shuffle() shuffles a sequence in place:

my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(f"Shuffled list: {my_list}")

sample() returns a new list containing a specified number of unique elements from a sequence:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random_sample = random.sample(my_list, k=3) # Picks 3 unique elements
print(f"Random sample: {random_sample}")

Working with Distributions

Beyond basic random number generation, the random module offers functions for various probability distributions:

uniform() generates a random floating-point number from a uniform distribution within a specified range:

random_uniform = random.uniform(2.5, 10.0)
print(f"Random uniform: {random_uniform}")

normalvariate() generates a random float from a normal (Gaussian) distribution:

random_normal = random.normalvariate(mu=0, sigma=1) # mu is the mean, sigma is the standard deviation
print(f"Random normal: {random_normal}")

These are just a few of the many capabilities offered by Python’s random module. Exploring the official documentation will unveil even more powerful tools for generating and manipulating random data in your Python programs. Remember that the numbers generated by random are pseudo-random, meaning they are deterministic and based on a seed value. For cryptographic applications requiring true randomness, consider using the secrets module instead.