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.random()
random_float print(f"Random float: {random_float}")
Need a random integer within a specific range? Use randint()
:
= random.randint(1, 10) # Generates a random integer between 1 and 10 (inclusive)
random_integer print(f"Random integer: {random_integer}")
For a random integer from a range excluding the upper bound, employ randrange()
:
= random.randrange(1, 10) # Generates a random integer between 1 and 9 (exclusive of 10)
random_integer_range print(f"Random integer (randrange): {random_integer_range}")
You can also generate random numbers from a given sequence using choice()
:
= ["apple", "banana", "cherry"]
my_list = random.choice(my_list)
random_choice print(f"Random choice: {random_choice}")
Shuffling and Sampling
The random
module also provides functions for manipulating sequences:
shuffle()
shuffles a sequence in place:
= [1, 2, 3, 4, 5]
my_list
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:
= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list = random.sample(my_list, k=3) # Picks 3 unique elements
random_sample 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(2.5, 10.0)
random_uniform print(f"Random uniform: {random_uniform}")
normalvariate()
generates a random float from a normal (Gaussian) distribution:
= random.normalvariate(mu=0, sigma=1) # mu is the mean, sigma is the standard deviation
random_normal 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.