Python random.sample() function
The random.sample()
function in Python is part of the built-in random
module and is used to generate a random sample from a specified population. Unlike random.choice()
, which selects a single random element, random.sample()
allows you to select multiple unique elements from a sequence without replacement. This means that the same element cannot be selected more than once in a single call.
Syntax
- Parameters:
population
: A sequence (like a list, tuple, or string) from which to sample.k
: The number of unique elements to select from the population. Must be less than or equal to the size of the population.
Return Value
- Returns a list of
k
unique elements chosen from thepopulation
.
Example Usage
Basic Example:
Sampling from a List of Strings:
Sampling with a Larger Population:
Attempting to Sample More Than Available: If you try to sample more elements than are available in the population, a
ValueError
will be raised:Seeding the Random Number Generator: You can use
random.seed()
to ensure reproducibility:
Summary
random.sample(population, k)
is a versatile function for selecting multiple unique elements from a given sequence.- It is useful in various applications, such as random sampling, simulations, and games.
- The function raises a
ValueError
ifk
is larger than the size of the population, so it's important to ensure that you specify a valid sample size.