Question
How can I retrieve a random item from the following Python list?
foo = ['a', 'b', 'c', 'd', 'e']
I want to choose one element at random from the list.
Short Answer
By the end of this page, you will understand how to select a random element from a Python list, which standard library function is usually used for this, how it works step by step, and what mistakes to avoid when the list may be empty or when reproducible results are needed.
Concept
In Python, a common way to get a random item from a list is to use the random module from the standard library. The most direct function for this is random.choice().
import random
foo = ['a', 'b', 'c', 'd', 'e']
item = random.choice(foo)
print(item)
random.choice(sequence) returns one randomly selected element from a non-empty sequence.
A sequence includes types like:
listtuplestr
This matters because choosing random data is extremely common in programming:
- picking a quiz question
- selecting a test case
- showing a random tip
- simulating events in a game
- sampling data for scripts
The key idea is simple: instead of manually generating an index yourself, Python provides a built-in tool that already does that safely and clearly.
If you only need one random element, random.choice() is usually the best and most readable option.
Mental Model
Think of a list like a bag of labeled balls:
'a''b''c''d''e'
Using random.choice(foo) is like reaching into the bag and pulling out one ball without caring which position it came from.
You do not need to count positions yourself unless you specifically want the index. Python does the pick for you.
Another way to picture it:
- the list is a row of boxes
- each box has an index
random.choice()secretly picks one valid box number- then returns the value inside that box
So the real job is not "find a random index" but "ask Python for one random element from this sequence."
Syntax and Examples
The basic syntax is:
import random
random.choice(sequence)
Basic example
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
Possible output:
c
If you run it again, you may get a different result.
Store the result in a variable
import random
colors = ['red', 'blue', 'green']
selected_color = random.choice(colors)
print(selected_color)
This is useful when you want to use the chosen value later.
Choosing from other sequence types
import random
print(random.choice((10, 20, 30)))
print(random.choice('hello'))
This works because tuples and strings are also sequences.
Step by Step Execution
Consider this code:
import random
foo = ['a', 'b', 'c', 'd', 'e']
item = random.choice(foo)
print(item)
Here is what happens step by step:
-
import random- Python loads the
randommodule so you can use its functions.
- Python loads the
-
foo = ['a', 'b', 'c', 'd', 'e']- A list named
foois created with 5 elements. - Their indexes are:
0 -> 'a'1 -> 'b'2 -> 'c'3 -> 'd'4 -> 'e'
- A list named
-
item = random.choice(foo)- Python checks that
foois not empty.
- Python checks that
Real World Use Cases
Random selection from a list appears in many real programs.
Showing a random message
A command-line app might display one random motivational message each time it starts.
import random
messages = ['Keep going!', 'Nice work!', 'You are improving!']
print(random.choice(messages))
Picking a random quiz question
An educational app may store questions in a list and choose one for the user.
Simulating game behavior
A game may choose a random enemy action:
- attack
- defend
- heal
Selecting sample data for tests
During development, you may want one random user ID or one random item from mock data.
Rotating content in web apps
A site might choose a random banner, tip, quote, or featured item.
Simple load distribution or experiments
In small scripts, developers may randomly pick from a list of options to test different paths.
Real Codebase Usage
In real codebases, developers usually use random selection in small, readable, defensive ways.
Common pattern: direct selection
import random
theme = random.choice(themes)
This is the most common pattern when the list is guaranteed to have values.
Guard clause for empty lists
A robust codebase often checks for empty input first.
import random
if not items:
return None
return random.choice(items)
This avoids runtime errors.
Validation before selection
If data comes from a file, API, or user input, developers often validate it first.
import random
if not isinstance(items, list) or not items:
raise ValueError('items must be a non-empty list')
return random.choice(items)
Reproducible behavior in tests
In automated tests, randomness is often seeded.
random
random.seed()
result = random.choice([, , ])
Common Mistakes
Here are common beginner mistakes when selecting a random list element in Python.
Mistake 1: Forgetting to import random
Broken code:
foo = ['a', 'b', 'c']
print(random.choice(foo))
Problem:
randomis not defined.
Fix:
import random
foo = ['a', 'b', 'c']
print(random.choice(foo))
Mistake 2: Calling choice() on an empty list
Broken code:
import random
foo = []
print(random.choice(foo))
Problem:
- This raises
IndexErrorbecause there is nothing to choose.
Fix:
import random
foo = []
if foo:
(random.choice(foo))
:
()
Comparisons
Here is how random.choice() compares with related approaches in Python.
| Approach | Best for | Returns | Notes |
|---|---|---|---|
random.choice(seq) | One random element | A value from the sequence | Most readable for a single item |
random.randrange(len(seq)) | One random index | An integer index | Useful only when you need the index |
random.sample(seq, k=1) | Unique random picks | A list | Returns a list, even for one item |
random.choices(seq, k=1) | Random picks with replacement | A list | Can repeat items when k > 1 |
Cheat Sheet
import random
random.choice(sequence)
Quick rules
random.choice()returns one random element from a non-empty sequence.- Works with:
- lists
- tuples
- strings
- You must
import randomfirst. - Empty sequences raise
IndexError.
Common examples
import random
foo = ['a', 'b', 'c', 'd', 'e']
item = random.choice(foo)
import random
index = random.randrange(len(foo))
item = foo[index]
Related functions
random.choice(seq) # one item
random.sample(seq, 2) # multiple unique items
random.choices(seq, k=2) # multiple items, repeats allowed
Empty-list safety
FAQ
How do I pick a random item from a Python list?
Use random.choice():
import random
item = random.choice(my_list)
What happens if the list is empty?
random.choice([]) raises IndexError. Check that the list is not empty before calling it.
Do I need to generate a random index manually?
No. If you only need the value, random.choice() is simpler and clearer.
Can I choose more than one random item?
Yes.
- Use
random.sample()for unique items. - Use
random.choices()if repeats are allowed.
Is random.choice() truly random?
It is suitable for normal programming tasks, but not for cryptographic or security-sensitive use.
How do I get the same random result during testing?
Set a seed first:
import random
random.seed(42)
Can I use random.choice() on tuples or strings?
Mini Project
Description
Build a simple Python script that displays a random prompt from a list of study tasks. This demonstrates how to store values in a list, choose one at random, and safely handle the case where the list might be empty.
Goal
Create a script that prints one random study task from a predefined list.
Requirements
- Create a list with at least five study tasks.
- Use Python's standard library to select one task at random.
- Print the selected task.
- Add a check so the program handles an empty list safely.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.