We're making some improvements. Some features may be temporarily unavailable.
intermediate20 min

List & Dict Comprehensions

Write concise, elegant Python with comprehensions

What Are Comprehensions?

Comprehensions are Python's way of creating new collections from existing ones — in a single, readable line. Once you learn them, you'll wonder how you lived without them.

Without comprehension:

squares = []
for i in range(10):
    squares.append(i ** 2)

With comprehension:

squares = [i ** 2 for i in range(10)]

Same result, but cleaner and often faster!

List Comprehensions

The basic syntax: [expression for item in iterable if condition]

List Comprehension Patterns

Output
Run your code to see output here

Check Your Understanding

What does [x for x in range(10) if x % 2 == 0] produce?

Dictionary Comprehensions

Same idea, but creates dictionaries: {key_expr: value_expr for item in iterable}

Dictionary Comprehension Patterns

Output
Run your code to see output here

Set Comprehensions

Sets use curly braces: {expression for item in iterable}

Set Comprehensions

Output
Run your code to see output here

Check Your Understanding

What's the difference between a list comprehension and a generator expression?

When NOT to Use Comprehensions

Comprehensions are great, but they shouldn't make your code unreadable:

# BAD — too complex, hard to understand
result = [x*y for x in range(10) for y in range(x) if x % 2 == 0 if y > 2]

# BETTER — use a regular loop for complex logic
result = []
for x in range(10):
    if x % 2 == 0:
        for y in range(x):
            if y > 2:
                result.append(x * y)

Exercise

Using a list comprehension, create a list of all numbers from 1 to 100 that are divisible by 3 AND 5. Then, using a dictionary comprehension, create a dictionary mapping each of those numbers to the string 'FizzBuzz'.

Python will load on first run

Performance Note

Comprehensions are implemented in C and are generally faster than equivalent for-loops with .append(). For large datasets, this can be significant:

# Loop:      ~0.15s
# List comp: ~0.08s  (≈2× faster)

Key Takeaways

  • List comprehension: [expr for item in iterable if cond]
  • Dict comprehension: {key: val for item in iterable}
  • Set comprehension: {expr for item in iterable}
  • They're faster and more readable than loops (when used appropriately)
  • Don't over-nest — if it's hard to read, use a regular loop
  • Comprehensions are one of Python's most "Pythonic" features

Questions & Discussion

Sign in to ask a question or join the discussion.

Loading comments...