The best way to learn Python list comprehensions isn't by memorizing syntax diagrams; it's by seeing them in action. If you have been writing for loops for basic tasks like doubling numbers or cleaning strings, you are about to save a lot of typing.
This guide provides 20 practical, beginner-friendly examples of list comprehensions. We have categorized them so you can find exactly what you need.
[!NOTE] Quick Reference
- Syntax:
[op(x) for x in list]- Filtering:
[x for x in list if check(x)]- Mapping:
[op(x) for x in list]
Table of Contents
- How to Read These Examples
- Category 1: Working with Numbers
- Category 2: String Manipulation
- Category 3: Type Conversion
- Category 4: Working with Objects/Dictionaries
- Category 5: Boolean Logic
- Practice Challenges
- Test Your Knowledge (Quiz)
How to Read These Examples
For every example, we will show you:
- The Task: What we want to achieve.
- The Code: The list comprehension solution.
- The Explanation: Why it works.
Here is a simple visualization of what is happening:
Input List: [1, 2, 3]
|
Operation: (x * 10)
|
Output List: [10, 20, 30]
Category 1: Working with Numbers
1. The "Hello World" (Copying a List)
Simply create a copy of a list.
nums = [1, 2, 3]
copy_nums = [x for x in nums]
# Result: [1, 2, 3]
Why: It iterates over nums, assigning each value to x, and putting x into the new list.
2. Doubling Numbers
Multiply every number by 2.
nums = [1, 2, 3, 4, 5]
doubled = [x * 2 for x in nums]
# Result: [2, 4, 6, 8, 10]
3. Squaring Numbers
Calculate the square ($x^2$) of numbers from 0 to 4.
# range(5) gives 0, 1, 2, 3, 4
squares = [x ** 2 for x in range(5)]
# Result: [0, 1, 4, 9, 16]
4. Adding a Constant
Add 10 to every number (e.g., adjusting scores).
scores = [85, 90, 78]
adjusted = [s + 10 for s in scores]
# Result: [95, 100, 88]
5. Calculating Remainders (Modulo)
Find the remainder when dividing by 3.
nums = [10, 11, 12, 13]
remainders = [n % 3 for n in nums]
# Result: [1, 2, 0, 1]
Category 2: String Manipulation
6. Uppercase Conversion
Convert a list of names to SHOUTY CAPITALS.
names = ["alice", "bob", "charlie"]
upper = [name.upper() for name in names]
# Result: ['ALICE', 'BOB', 'CHARLIE']
7. Extract First Character (Initials)
Get the first letter of each word.
words = ["Apple", "Banana", "Cherry"]
initials = [w[0] for w in words]
# Result: ['A', 'B', 'C']
8. Measuring Lengths
Create a list of numbers representing word lengths.
animals = ["cat", "horse", "elephant"]
lengths = [len(a) for a in animals]
# Result: [3, 5, 8]
9. String Formatting (f-strings)
Add a prefix to every item.
users = ["user1", "user2"]
emails = [f"{u}@example.com" for u in users]
# Result: ['user1@example.com', 'user2@example.com']
10. Cleaning Whitespace
Strip spaces from messy user input.
raw_data = [" hello ", "world ", " python "]
clean = [s.strip() for s in raw_data]
# Result: ['hello', 'world', 'python']
Category 3: Type Conversion
11. String to Integer
Convert a list of numeric strings into actual integers for math.
str_nums = ["10", "20", "30"]
int_nums = [int(x) for x in str_nums]
# Result: [10, 20, 30]
12. Integer to Float
Convert integers to floating-point numbers.
prices = [10, 20, 30]
float_prices = [float(p) for p in prices]
# Result: [10.0, 20.0, 30.0]
13. Boolean to Integer
Convert True/False to 1/0. Detailed for data science.
flags = [True, False, True]
binary = [int(f) for f in flags]
# Result: [1, 0, 1]
14. List of Lists to Lengths
Convert complex structures to simple metrics.
nested = [[1, 2], [3, 4, 5], []]
counts = [len(sublist) for sublist in nested]
# Result: [2, 3, 0]
Category 4: Objects & Dictionaries
15. Extracting Dictionary Values
Get a specific field from a list of dicts (e.g., API response).
users = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'}
]
names = [u['name'] for u in users]
# Result: ['Alice', 'Bob']
16. Extracting Object Attributes
Assuming you have a class User with a .email attribute.
# emails = [user.email for user in user_list]
17. Creating Tuples (Pairing Data)
Create a list of (index, value) pairs using enumerate.
chars = ['a', 'b', 'c']
indexed = [(i, c) for i, c in enumerate(chars)]
# Result: [(0, 'a'), (1, 'b'), (2, 'c')]
Category 5: Boolean Logic
18. Checking Truthiness
Convert values to booleans to check if they are empty or not.
values = ["text", "", 1, 0, []]
is_truthy = [bool(v) for v in values]
# Result: [True, False, True, False, False]
19. Type Checking
Check if items are numbers.
mixed = [1, "a", 2.5]
is_number = [isinstance(x, (int, float)) for x in mixed]
# Result: [True, False, True]
20. Comparison Checks
Check if numbers are positive.
nums = [10, -5, 0]
is_positive = [n > 0 for n in nums]
# Result: [True, False, False]
Practice Challenges
Ready to test yourself? Try these without looking at the solutions immediately.
- Challenge 1: Create a list of the first 3 letters of each month name.
['January', 'February']->['Jan', 'Feb']. - Challenge 2: Create a list that contains
Trueif a word starts with "A", andFalseotherwise. - Challenge 3: Given
range(5), create a list of strings:["Number 0", "Number 1", "Number 2"...].
Test Your Knowledge
Summary
You have just seen 20 ways to avoid writing a generic for loop. The key is to recognize the pattern: whenever you want to transform a list into another list of the same length, a list comprehension is the answer.
Next Steps:
- Learn how to filter items: If Conditions
- Learn complex logic: If-Else Statements