Python random.choice() function
The random.choice()
function in Python is part of the built-in random
module and is used to select a random element from a non-empty sequence, such as a list, tuple, or string. This function is particularly useful when you want to randomly pick an item from a collection of items.
Syntax
- Parameters:
sequence
: A non-empty sequence (like a list, tuple, or string) from which to select an item.
Return Value
- Returns a randomly selected element from the provided sequence.
Example Usage
Basic Example with a List:
Using with a String: You can use
random.choice()
with strings, treating the string as a sequence of characters:Selecting Random Elements from a Tuple:
Multiple Random Selections: If you need to select multiple random items (with replacement), you can use a loop:
Example output might look like:
Seeding the Random Number Generator: You can use
random.seed()
to ensure reproducibility:
Summary
random.choice(sequence)
is a simple and effective way to select a random element from a non-empty sequence.- It is commonly used in scenarios such as games, simulations, and random sampling.
- If the sequence is empty,
random.choice()
will raise anIndexError
, so it's a good practice to ensure that the sequence is not empty before calling this function.