random
ModulePython's random
module is a powerful tool for generating pseudo-random numbers, essential for simulations, games, data analysis, and more. This article explores the module's functionalities, providing a comprehensive guide to its distributions and functions. It's crucial to understand that the random
module is not suitable for cryptographic purposes; for security-sensitive applications, refer to the secrets
module.
The random
module provides functions for generating random numbers from various distributions. It relies on the Mersenne Twister as its core generator, producing 53-bit precision floats with a long period. All module functions ultimately depend on the random()
function, which generates a random float uniformly in the range of 0.0 <= X < 1.0.
These functions manage the state of the random number generator.
random.seed(a=None, version=2)
: Initializes the random number generator.
a
is omitted or None
, the current system time is used, or randomness sources provided by the OS.a
is an integer, it is used directly as the seed.version=2
(default) uses all bits from strings, bytes, or bytearrays for seeding.random.getstate()
: Returns an object capturing the current internal state of the generator. This is useful for saving and restoring the state of the generator.random.setstate(state)
: Restores the internal state of the generator to a previously saved state obtained via getstate()
.import random
# Seed the generator
random.seed(42)
# Get the current state
state = random.getstate()
# Generate some random numbers
print(random.random())
print(random.randint(1, 10))
# Restore the state
random.setstate(state)
# Generate the same random numbers again
print(random.random())
print(random.randint(1, 10))
random.randbytes(n)
: Generates n
random bytes. For security-sensitive byte generation, the module secrets
should be used.These functions generate random integers within specified ranges.
random.randrange(stop)
or random.randrange(start, stop[, step])
: Returns a randomly selected element from range(start, stop, step)
. It's optimized for large ranges, being more efficient than choice(range(start, stop, step))
.random.randint(a, b)
: Returns a random integer N
such that a <= N <= b
. It's an alias for randrange(a, b+1)
.random.getrandbits(k)
: Returns a non-negative Python integer with k
random bits. This is particularly useful for generating very large random integers.import random
# Generate a random integer between 1 and 10
random_integer = random.randint(1, 10)
print(f"Random integer: {random_integer}")
# Generate a random number from a range with a step
random_range = random.randrange(0, 100, 5)
print(f"Random number from range: {random_range}")
# Generate number with 20 random bits
random_bits = random.getrandbits(20)
print(f"Random bits: {random_bits}")
These functions operate on sequences like lists and tuples.
random.choice(seq)
: Returns a random element from the non-empty sequence seq
. Raises IndexError
if seq
is empty.random.choices(population, weights=None, *, cum_weights=None, k=1)
: Returns a k
-sized list of elements chosen from the population
with replacement. You can specify weights
or cum_weights
for weighted random selection.random.shuffle(x)
: Shuffles the sequence x
in place, modifying the original list. Use sample(x, k=len(x))
to shuffle an immutable sequence and return a new shuffled list.random.sample(population, k, *, counts=None)
: Returns a k
-length list of unique elements chosen from the population
sequence without replacement. Used for random sampling. The counts
parameter allows specifying multiple occurrences of elements.import random
my_list = [1, 2, 3, 4, 5]
# Choose a random element
random_element = random.choice(my_list)
print(f"Random element: {random_element}")
# Choose multiple elements with replacement
random_choices = random.choices(my_list, k=3)
print(f"Random choices: {random_choices}")
# Shuffle the list in place
random.shuffle(my_list)
print(f"Shuffled list: {my_list}")
# Sample without replacement
random_sample = random.sample(my_list, k=2)
print(f"Random sample: {random_sample}")
random.binomialvariate(n=1, p=0.5)
: Returns the number of successes for n
independent trials with a probability of success p
in each trial (Binomial distribution).The random
module also offers a variety of real-valued distribution functions (the documentation source was cut off). Consult the Python documentation to discover more of these functions.
The random
module allows you to create your own random number generators by instantiating the random.Random
class. This allows you to maintain separate states for different parts of your application, or to use a different underlying generator if needed. You can even subclass random.Random
to implement your own custom generator.
import random
# Create a new random number generator instance
my_generator = random.Random()
# Seed the generator
my_generator.seed(123)
# Generate random numbers using the new generator
print(my_generator.random())
print(my_generator.randint(1, 10))
Because the random number generators in the random
module are pseudo-random, it's possible to reproduce sequences of random numbers by using the same seed value. This can be useful for debugging or for creating deterministic simulations.
As mentioned earlier, the pseudo-random generators of this module should not be used for security purposes. For generating secure random numbers, use the secrets
module.
The official Python documentation includes recipes and examples that further explain how to use the random
module effectively. Experiment with these examples to build your understanding of the module's capabilities. Also, consider using the random
module from the command line, see Command-line usage and Command-line example
By leveraging the functions and distributions of the random
module, you can easily incorporate randomness into your Python projects, opening up opportunities for simulations, games, and data exploration. Remember to choose the right tool for the job, and keep security considerations in mind when generating random numbers.