To randomly select an item from a list in Python, you can use the random
module. Here are the most common methods:
1. Select a Single Random Item
Use random.choice()
for a single random element:
import random
my_list = ["apple", "banana", "cherry", "date"]
# Randomly select one item
random_item = random.choice(my_list)
print(random_item) # Example output: "banana"
2. Select Multiple Unique Random Items
Use random.sample()
to select multiple unique items (no duplicates):
import random
# Select 2 unique random items
random_items = random.sample(my_list, 2)
print(random_items) # Example: ["cherry", "apple"]
3. Select Multiple Items (With Possible Duplicates)
Use random.choices()
(Python 3.6+) to allow duplicates:
import random
# Select 3 items (duplicates possible)
random_selections = random.choices(my_list, k=3)
print(random_selections) # Example: ["banana", "banana", "date"]
4. Shuffle the List and Select
Randomize the list order and pick items:
import random
# Shuffle the list in place
random.shuffle(my_list)
print(my_list[0]) # First item after shuffling
# Or copy and shuffle:
shuffled = my_list.copy()
random.shuffle(shuffled)
print(shuffled.pop()) # Take the last item after shuffling
Key Notes
- Dependencies:
random
is part of Python’s standard library—no installation needed. - Edge Cases:
random.sample()
requires the sample sizek
≤ list length.random.choice()
raisesIndexError
if the list is empty.- Reproducibility: Seed the generator for reproducible results:
random.seed(42) # Initialize with a fixed seed
Full Example
import random
# Example list
fruits = ["apple", "banana", "cherry", "date"]
# Check if the list is non-empty
if fruits:
# Single random item
print("Random fruit:", random.choice(fruits))
# Two unique items
print("Two unique fruits:", random.sample(fruits, 2))
# Three selections (duplicates allowed)
print("Three picks (may repeat):", random.choices(fruits, k=3))
else:
print("The list is empty.")
Summary
- Single Item:
random.choice()
- Multiple Unique Items:
random.sample()
- Multiple Items (Duplicates Allowed):
random.choices()
- Shuffling:
random.shuffle()
orrandom.sample()
with full length.