List
Comprehensions
Master Python's most elegant one-liner for mapping and filtering data: transform collections with concise, readable expressions.
What Is a List Comprehension?
A list comprehension is a compact way to create a new list by applying an expression to each item in an existing iterable. Instead of writing a multi-line loop, you describe the entire transformation in a single line inside square brackets.
squares = [x ** 2 for x in range(6)] # Result: [0, 1, 4, 9, 16, 25]
Why They Matter
From Loop to Comprehension
result = [] for x in range(6): result.append(x ** 2)
result = [x ** 2 for x in range(6)]
The Anatomy of a Comprehension
Adding a Filter with if
evens = [x for x in range(10) if x % 2 == 0] # Result: [0, 2, 4, 6, 8]
Mapping vs Filtering
| Mapping | Filtering | |
|---|---|---|
| Purpose | Transform each item | Select certain items |
| Output size | Same as input | Smaller or equal |
| Key part | expression | if condition |
| Example | [x*2 for x in L] |
[x for x in L if x>0] |
How Data Flows
How to Write a Comprehension
x, word, num.if condition.[expression for var in source if cond].Example 1: Mapping Strings
Task: Convert a list of names to uppercase.
names = ["alice", "bob", "carol"] upper = [name.upper() for name in names] # Result: ["ALICE", "BOB", "CAROL"]
Example 2: Filtering Numbers
Task: Keep only the positive numbers from a list.
nums = [-3, -1, 0, 2, 7, -5, 4] positives = [n for n in nums if n > 0] # Result: [2, 7, 4]
Example 3: Map + Filter Combined
Task: Square only the even numbers from 0-9.
result = [x ** 2 for x in range(10) if x % 2 == 0] # Step by step: # range(10) → 0,1,2,3,4,5,6,7,8,9 # if x % 2 == 0 → keeps 0,2,4,6,8 # x ** 2 → squares them # Result: [0, 4, 16, 36, 64]
Strings Are Iterables Too
You can iterate over any iterable, not just lists. Strings, tuples, ranges, and even files work as sources.
word = "python" # Extract vowels vowels = [ch for ch in word if ch in "aeiou"] # Result: ["o"] # Capitalize each character caps = [ch.upper() for ch in word] # Result: ["P","Y","T","H","O","N"]
if/else in the Expression
An if/else in the expression position transforms every item (no filtering). It goes before the for.
nums = [1, -2, 3, -4, 5] labels = ["pos" if n > 0 else "neg" for n in nums] # Result: ["pos","neg","pos","neg","pos"]
Common Mistakes
[x for x in L if x > 0 else -1] is a SyntaxError. The else must go before for.[ ] around the comprehension creates a generator, not a list. Use list(...) if needed.Quick Reference Table
| Pattern | Syntax | Effect |
|---|---|---|
| Map only | [f(x) for x in L] |
Transform every item |
| Filter only | [x for x in L if cond] |
Keep matching items |
| Map + Filter | [f(x) for x in L if cond] |
Filter, then transform |
| Conditional Map | [A if c else B for x in L] |
Choose per item, keep all |
Question 1 of 5
What does the following code produce?[x * 3 for x in [1, 2, 3]]
Question 2 of 5
Which comprehension keeps only strings with more than 4 characters?
len(s) > 4. Option A returns lengths, not strings. Option B compares the string itself to 4. Option D has invalid syntax (missing else).Question 3 of 5
Where does if/else go when you want to conditionally transform every item without dropping any?
for) maps every item to one of two values. An if after the iterable filters items out: it cannot have an else.Question 4 of 5
What is the output of:[ch for ch in "hello" if ch not in "aeiou"]
ch not in "aeiou" removes vowels. From "hello", the consonants are "h", "l", "l". The result is a list of characters, not a string.Question 5 of 5
Which line of code is equivalent to:["even" if x % 2 == 0 else "odd" for x in range(4)]