Of course! Picking random elements in Python is a common task, and the random module is your best friend. Here’s a comprehensive guide covering the most common use cases, from simple picks to more advanced sampling.
The Short Answer: The Most Common Methods
For 90% of use cases, you'll only need these two functions from the random module.
random.choice(): Pick one random item from a list.random.sample(): Pick multiple unique items from a list.
Picking One Random Item
Use random.choice() when you just need to pick a single item at random from a sequence (like a list, tuple, or string).
How to use it:
import random
# Define a list of options
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
# Pick one random fruit
random_fruit = random.choice(fruits)
print(f"The list of fruits is: {fruits}")
print(f"The randomly chosen fruit is: {random_fruit}")
Example Output:
The list of fruits is: ['apple', 'banana', 'cherry', 'date', 'elderberry']
The randomly chosen fruit is: cherry
Picking Multiple Unique Items
Use random.sample() when you want to pick a specific number of items, and it's important that each item is only picked once (no duplicates).
How to use it:
The function takes two arguments: the population (your list) and k (the number of items to pick).
import random
# Define a list of options
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
# Pick 3 unique random fruits
random_fruits = random.sample(fruits, k=3)
print(f"The list of fruits is: {fruits}")
print(f"The 3 randomly chosen fruits are: {random_fruits}")
Example Output:
The list of fruits is: ['apple', 'banana', 'cherry', 'date', 'elderberry']
The 3 randomly chosen fruits are: ['date', 'apple', 'elderberry']
Picking Multiple Items with Repetition (Allowing Duplicates)
Use random.choices() (note the 's' at the end) when you want to pick multiple items and you allow for the same item to be picked more than once.
How to use it:
It's similar to sample(), but you can also specify weights for each item to make some more likely to be chosen than others.
import random
# Define a list of options
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
# Pick 5 random fruits, allowing for duplicates
random_fruits_with_replacement = random.choices(fruits, k=5)
print(f"The list of fruits is: {fruits}")
print(f"The 5 randomly chosen fruits (with possible duplicates) are: {random_fruits_with_replacement}")
Example Output:
The list of fruits is: ['apple', 'banana', 'cherry', 'date', 'elderberry']
The 5 randomly chosen fruits (with possible duplicates) are: ['banana', 'cherry', 'banana', 'apple', 'banana']
Example with Weights:
You can pass a weights argument to influence the probability of each item being chosen.
# 'apple' has a 50% chance, 'banana' 30%, 'cherry' 20%, and 'date'/'elderberry' almost 0%
weighted_fruits = random.choices(fruits, weights=[50, 30, 20, 1, 1], k=10)
print(f"Weighted random picks: {weighted_fruits}")
Shuffling a List (In-Place)
If you don't need to pick items but want to randomize the order of an entire list, use random.shuffle(). This function modifies the list in-place and returns None.
How to use it:
import random
# Define a list of options
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(f"Original list: {numbers}")
# Shuffle the list in-place
random.shuffle(numbers)
print(f"Shuffled list: {numbers}")
Example Output:
Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Shuffled list: [3, 10, 7, 1, 5, 9, 2, 8, 4, 6]
Complete Example: A Simple Random Number Guessing Game
This example combines several of the concepts above.
import random
def guess_the_number_game():
"""A simple game where the user has to guess a random number."""
# 1. Pick a random integer between 1 and 100
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("Welcome to the 'Guess the Number' game!")
print(f"I'm thinking of a number between 1 and 100. You have {max_attempts} attempts.")
while attempts < max_attempts:
try:
# Get user input
guess_str = input(f"Attempt {attempts + 1}/{max_attempts}. Enter your guess: ")
guess = int(guess_str)
attempts += 1
# Check the guess
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print(f"Congratulations! You guessed it in {attempts} attempts!")
return # End the game on success
except ValueError:
print("Invalid input. Please enter a number.")
# We don't count this as an attempt
attempts -= 1
# If the loop finishes, the user lost
print(f"\nGame over! The secret number was {secret_number}.")
# Run the game
guess_the_number_game()
Summary Table
| Function | What it Does | Example | Returns |
|---|---|---|---|
random.choice(seq) |
Picks one random item from a sequence. | random.choice(['A', 'B', 'C']) |
A single item (e.g., 'B') |
random.sample(pop, k) |
Picks k unique items from a population. |
random.sample([1,2,3,4], k=2) |
A new list (e.g., [3, 1]) |
random.choices(pop, k, weights=...) |
Picks k items, with replacement (duplicates allowed). |
random.choices(['R','G','B'], k=5) |
A new list (e.g., ['G', 'B', 'G', 'R', 'G']) |
random.shuffle(lst) |
Randomly shuffles a list in-place. | my_list = [1,2,3]; random.shuffle(my_list) |
None (modifies my_list) |
random.randint(a, b) |
Returns a random integer N such that a <= N <= b. |
random.randint(10, 20) |
An integer (e.g., 15) |
random.random() |
Returns a random float between 0.0 (inclusive) and 1.0 (exclusive). | random.random() |
A float (e.g., 842364) |
Important Note on "True" Randomness
The Python random module uses a pseudo-random number generator (PRNG). This is perfectly fine for games, simulations, and most general-purpose programming. However, for security-sensitive applications like generating passwords, API keys, or security tokens, you should use the secrets module, which is designed to generate cryptographically strong random numbers.
Example with secrets (for passwords):
import secrets
import string
# Generate a 16-character random password
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(16))
print(f"Securely generated password: {password}") 