01 / 20

List
Comprehensions

Master Python's most elegant one-liner for mapping and filtering data: transform collections with concise, readable expressions.

Python

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.

Python
squares = [x ** 2 for x in range(6)]
# Result: [0, 1, 4, 9, 16, 25]

Why They Matter

Concise
Replace 3-4 lines of loop code with a single expressive line.
Readable
Clearly communicates intent: "build a list from these items."
Faster
Python optimizes list comprehensions internally, often outperforming explicit loops.

From Loop to Comprehension

Traditional Loop
result = []
for x in range(6):
    result.append(x ** 2)
List Comprehension
result = [x ** 2
          for x in range(6)]

The Anatomy of a Comprehension

[ expression for variable in iterable ]
▲ Output expression
▲ Loop variable
▲ Source iterable

Adding a Filter with if

[ expression for var in iterable if condition ]
▲ Transform
▲ Source
▲ Guard clause
Python
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

Source [0, 1, 2, 3, 4, 5] if x % 2 == 0 rejected: 1, 3, 5 kept: 0, 2, 4 x ** 2 [0, 4, 16] Result [x ** 2 for x in range(6) if x % 2 == 0]

How to Write a Comprehension

1
Identify the source. What list, range, or iterable are you looping over?
2
Name the loop variable. Pick a clear name: x, word, num.
3
Write the output expression. What do you want each element to become?
4
Add a filter (optional). Do you need to keep only certain items? Add if condition.
5
Wrap in brackets. Assemble: [expression for var in source if cond].

Example 1: Mapping Strings

Task: Convert a list of names to uppercase.

Python
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.

Python
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.

Python
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.

Python
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.

Python
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

✕ Wrong if/else position
Writing [x for x in L if x > 0 else -1] is a SyntaxError. The else must go before for.
✕ Missing brackets
Forgetting the [ ] around the comprehension creates a generator, not a list. Use list(...) if needed.
✕ Overcomplicating
Nesting too many loops or conditions in one comprehension hurts readability. If it is hard to read, use a regular loop instead.

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?

Question 3 of 5

Where does if/else go when you want to conditionally transform every item without dropping any?

Question 4 of 5

What is the output of:
[ch for ch in "hello" if ch not in "aeiou"]

Question 5 of 5

Which line of code is equivalent to:
["even" if x % 2 == 0 else "odd" for x in range(4)]