Python List Comprehensions: The Complete Guide
Everything you need to know about list comprehensions in Python — from the basic syntax to nested comprehensions, dict and set comprehensions, and when not to use them.

What Is a List Comprehension?
A list comprehension is a concise way to create a new list by applying an expression to each item in an iterable, optionally filtered by a condition. It is one of the most Pythonic features of the language and is used constantly in real-world code.
Without a comprehension:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n)
print(evens) # [2, 4, 6, 8, 10]
With a comprehension:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
Same result, one line, no temporary variables.
The Syntax
The full template is:
[expression for item in iterable if condition]
- expression: what goes into the new list (can transform the item)
- item: the loop variable
- iterable: any sequence — list, range, string, file lines, etc.
- condition (optional): a filter; items where this is
Falseare skipped
Practical Examples
Transform and filter at once
words = ["hello", "world", "python", "is", "great"]
long_upper = [w.upper() for w in words if len(w) > 4]
print(long_upper) # ['HELLO', 'WORLD', 'PYTHON', 'GREAT']
Flatten a list of lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [n for row in matrix for n in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Build ranges of derived values
squares = [x ** 2 for x in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Conditional expression (ternary) inside a comprehension
labels = ["even" if n % 2 == 0 else "odd" for n in range(1, 8)]
print(labels) # ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Dictionary and Set Comprehensions
The same idea works for dictionaries and sets.
Dict comprehension
names = ["Alice", "Bob", "Charlie"]
name_lengths = {name: len(name) for name in names}
print(name_lengths) # {'Alice': 5, 'Bob': 3, 'Charlie': 7}
Set comprehension
sentence = "the cat sat on the mat"
unique_words = {word for word in sentence.split()}
print(unique_words) # {'the', 'cat', 'sat', 'on', 'mat'} — order may vary
Generator Expressions
Swap [] for () and you get a generator expression — it produces values lazily instead of building the whole list in memory. Useful for large sequences.
total = sum(x ** 2 for x in range(1_000_000)) # never builds a 1M-item list
When NOT to Use Comprehensions
Comprehensions can be abused. Avoid them when:
- The logic is complex enough that a loop is clearer. Readability > brevity.
- You have deeply nested comprehensions. Two levels is usually the limit.
- You have side effects. Do not use a comprehension just to call a function for its effect — use a loop.
# Bad: comprehension with side effects
[print(x) for x in range(5)] # Works but confusing
# Good: just use a loop
for x in range(5):
print(x)
Performance
Comprehensions are generally faster than equivalent for loops with append() because the list is constructed in a single C-level operation. The difference matters when processing large lists:
import timeit
loop_time = timeit.timeit(
"r = []; [r.append(x*2) for x in range(10000)]", number=1000
)
comp_time = timeit.timeit(
"[x*2 for x in range(10000)]", number=1000
)
print(f"Loop: {loop_time:.3f}s")
print(f"Comprehension: {comp_time:.3f}s")
# Comprehension is typically 20-30% faster
Summary
| Feature | Syntax |
|---|---|
| Basic list comprehension | [expr for x in it] |
| With filter | [expr for x in it if cond] |
| Nested | [expr for x in it1 for y in it2] |
| Dict comprehension | {k: v for x in it} |
| Set comprehension | {expr for x in it} |
| Generator | (expr for x in it) |
List comprehensions are one of the first things that makes Python code look and feel professional. If you are working through Python Foundry's certification course, you will encounter them starting in the Data Structures module and use them throughout.
Share this article
Comments
No comments yet
Sign in to join the conversation.
Sign in to commentBe the first to comment.


