What Are List Comprehensions?
List comprehensions are one of Python's most elegant features — a concise way to create lists from existing iterables. Instead of writing a multi-line for loop, you can express the same logic in a single, readable line.
The basic syntax looks like this:
[expression for item in iterable if condition]
Basic List Comprehension Examples
Let's start with a simple example: squaring numbers from 0 to 9.
The traditional loop approach:
squares = []
for x in range(10):
squares.append(x ** 2)
The list comprehension approach:
squares = [x ** 2 for x in range(10)]
Both produce [0, 1, 4, 9, 16, 25, 36, 49, 64, 81], but the comprehension is more Pythonic and often faster.
Adding Conditions (Filtering)
You can filter elements by adding an if clause at the end:
# Only even squares
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
# Output: [0, 4, 16, 36, 64]
You can also use if/else (ternary) inside the expression part:
labels = ["even" if x % 2 == 0 else "odd" for x in range(6)]
# Output: ['even', 'odd', 'even', 'odd', 'even', 'odd']
Nested List Comprehensions
List comprehensions can be nested to handle multi-dimensional data, like flattening a 2D matrix:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Tip: Read nested comprehensions left to right — the outer loop comes first.
Set and Dictionary Comprehensions
The same concept applies to sets and dictionaries:
# Set comprehension (unique values)
unique_lengths = {len(word) for word in ["apple", "bat", "cat", "avocado"]}
# Dictionary comprehension
word_lengths = {word: len(word) for word in ["apple", "bat", "cat"]}
# Output: {'apple': 5, 'bat': 3, 'cat': 3}
When NOT to Use List Comprehensions
List comprehensions are powerful, but they're not always the right tool:
- Complex logic: If your expression needs multiple lines of logic, a regular loop is more readable.
- Large datasets: For huge datasets, consider a generator expression
(x for x in ...)instead — it's memory-efficient. - Side effects: Don't use comprehensions purely for side effects (like printing). Use a loop instead.
Performance Considerations
List comprehensions are generally faster than equivalent for loops because they're optimized at the C level in CPython. However, the difference is usually negligible for small datasets. For very large datasets, generator expressions are your best bet since they produce items lazily without building the entire list in memory.
Quick Reference
| Type | Syntax |
|---|---|
| List | [expr for x in iterable] |
| Filtered List | [expr for x in iterable if cond] |
| Set | {expr for x in iterable} |
| Dict | {k: v for x in iterable} |
| Generator | (expr for x in iterable) |
Mastering list comprehensions will make your Python code shorter, cleaner, and more idiomatic. Start by replacing simple append-in-a-loop patterns and work your way up from there.