Skip to content

List Comprehensions

Write concise, readable list transformations with comprehensions, filters, and nested loops.

What you'll learn

  • Write basic list comprehensions
  • Add conditional filters to comprehensions
  • Use nested comprehensions for 2D data
  • Apply dict and set comprehensions
  • Know when comprehensions help vs hurt readability

Concept

Basic Syntax

A list comprehension creates a new list by applying an expression to each item in an iterable. It replaces the verbose for-loop + append pattern:

# Old way — verbose
squares = []
for x in range(10):
    squares.append(x ** 2)

# Comprehension — concise and readable
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The general form is: [expression for item in iterable]. Read it left-to-right: "give me the expression, for each item in the iterable." Comprehensions are both faster (optimized internally) and more readable than the equivalent loop.

Conditional Filters

Add an if clause to filter which items are included:

# Even numbers only
evens = [x for x in range(20) if x % 2 == 0]

# Strings longer than 3 characters
words = ["cat", "house", "dog", "elephant", "bee"]
long_words = [w for w in words if len(w) > 3]
# ['house', 'elephant']

The filter goes after the for clause. Only items where the condition is True are included in the result.

Conditional Expression (Ternary)

Use an if/else inside the expression to transform values conditionally:

# Label numbers as even or odd
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
# ['even', 'odd', 'even', 'odd', 'even']

# Replace negatives with 0
numbers = [1, -2, 3, -4, 5]
clamped = [x if x >= 0 else 0 for x in numbers]
# [1, 0, 3, 0, 5]

Note the position: [expr_if_true if condition else expr_if_false for item in iterable]. This is different from the filter — the ternary transforms every item, while the filter excludes items.

Nested Comprehensions

You can nest loops for multi-dimensional data:

# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Create a 3x3 identity matrix
identity = [[1 if i == j else 0 for j in range(3)] for i in range(3)]
# [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Read nested comprehensions from left to right, outer loop first. They can get hard to read — if you need more than two levels, use a regular loop for clarity.

Dict Comprehensions

# Square each number as a key-value pair
squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Invert a dictionary (swap keys and values)
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b', 3: 'c'}

# Filter dict items
prices = {"apple": 1.5, "banana": 0.5, "cherry": 3.0}
expensive = {k: v for k, v in prices.items() if v > 1.0}
# {'apple': 1.5, 'cherry': 3.0}

Set Comprehensions

# Unique lengths of words
words = ["cat", "dog", "house", "bee", "tree"]
unique_lengths = {len(w) for w in words}
# {3, 4, 5} — a set, duplicates removed

Use curly braces {} for set comprehensions and {k: v ...} for dict comprehensions.

Generator Expressions

Replace the square brackets with parentheses to create a generator — it produces items lazily, one at a time, saving memory:

# List comprehension — all values in memory at once
squares_list = [x ** 2 for x in range(1000000)]

# Generator expression — produces values on demand
squares_gen = (x ** 2 for x in range(1000000))
print(sum(squares_gen))  # computes without storing all values

Generators are ideal for large datasets and pipelines where you do not need all values simultaneously.

When NOT to Use Comprehensions

Comprehensions are great, but they can hurt readability when:

  • The expression is complex or has multiple function calls
  • You need more than two nested loops
  • You need side effects (comprehensions should be pure)
# Too complex — use a regular loop
# result = [transform(x) for x in data if validate(x) and not skip(x) and x.priority > 5]

# Better:
result = []
for x in data:
    if not validate(x) or skip(x):
        continue
    if x.priority <= 5:
        continue
    result.append(transform(x))

Rule of thumb: if you cannot read it in one glance, use a regular for loop.

Example

              # Basic comprehension
squares = [x ** 2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Conditional filter
evens = [x for x in range(20) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Ternary expression
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(labels)  # ['even', 'odd', 'even', 'odd', 'even']

# String filtering
words = ["cat", "house", "dog", "elephant", "bee"]
long_words = [w.upper() for w in words if len(w) > 3]
print(long_words)  # ['HOUSE', 'ELEPHANT']

# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Dict comprehension — invert a dict
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted)  # {1: 'a', 2: 'b', 3: 'c'}

# Set comprehension — unique lengths
word_list = ["cat", "dog", "house", "bee", "tree"]
unique_lengths = {len(w) for w in word_list}
print(unique_lengths)  # {3, 4, 5}

# Generator expression — memory efficient
total = sum(x ** 2 for x in range(100))
print(f"Sum of squares 0-99: {total}")

# Practical: extract emails from user dicts
users = [
    {"name": "Ada", "email": "ada@x.com", "active": True},
    {"name": "Bob", "email": "bob@x.com", "active": False},
    {"name": "Cy", "email": "cy@x.com", "active": True},
]
active_emails = [u["email"] for u in users if u["active"]]
print(active_emails)  # ['ada@x.com', 'cy@x.com']
            

Demonstrates basic comprehensions, conditional filters, ternary expressions, string processing, flattening a 2D list, dict inversion, set deduplication, generator expressions with sum(), and a practical real-world example extracting active user emails.

Try it

  • Text Counter

    Comprehensions are perfect for transforming counted text data.

  • JSON Formatter

    Dict comprehensions transform JSON-like data structures.

Common mistakes

The mistake

Making comprehensions too complex to read in one glance

The fix

If a comprehension has multiple conditions, nested loops, or complex expressions, it hurts readability. Rewrite as a regular for loop. The rule: if you cannot read it at a glance, use a loop. Readability beats cleverness (PEP 8).

The mistake

Using a list comprehension when a generator expression would save memory

The fix

[expr for x in data] creates the entire list in memory. (expr for x in data) creates a generator that yields items lazily. For large data processed in a pipeline (e.g., sum()), use a generator expression to avoid storing all values.

Related Cheatsheets

Practice List Comprehensions

3 exercises

Practice List Comprehensions

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors