# Comprehensions: List, Dict & Set Expressions

> Master Python comprehensions: declarative syntax for creating lists, dictionaries, and sets at C-speed, filtering elements with conditions, avoiding complex nesting traps, and choosing when a traditional loop is more readable.

Subject: Python | Lesson 22 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/list-comprehensions
Previous: [Exception Handling: try, except, else, finally](https://codewithanimation.in/python/exceptions.md) | Next: [Generators & The Lazy yield Protocol](https://codewithanimation.in/python/generators.md)

## Declarative Collection Construction

Comprehensions provide a concise, declarative syntax for transforming and filtering an iterable into a new collection in a single line.

The anatomy of a list comprehension follows a clean pattern: `[expression for item in iterable if condition]`. The expression defines the transformation, the `for` clause iterates over the source, and the optional `if` clause acts as a filter.

Python also natively supports dictionary comprehensions `{key_expr: val_expr for item in iterable}` and set comprehensions `{expr for item in iterable}`, sharing the exact same pipeline semantics.

## Why Comprehensions Outperform append() Loops

In a traditional `for` loop that populates a list, every element addition invokes `list.append()`. In CPython, each call requires looking up the `.append` attribute on the list object and executing a full Python function call frame.

In contrast, list comprehensions are compiled directly into a specialized bytecode loop using the optimized `LIST_APPEND` C opcode. This avoids Python-level attribute lookups and function call overhead.

As a result, list comprehensions typically run 25% to 35% faster than equivalent imperative `for` loops in standard CPython.

## Filtering, Dict Inversion, and Conditional Expressions

To filter items, place the `if` clause at the end: `[x for x in numbers if x % 2 == 0]` keeps only even numbers.

If you need an `if-else` ternary transform, place it before the `for`: `[x if x > 0 else 0 for x in numbers]`. Here, the condition determines the value produced for every item rather than filtering.

Dictionary comprehensions are particularly powerful for transforming key-value pairs: `{user['id']: user for user in user_list}` creates an O(1) lookup index, while `{v: k for k, v in code_map.items()}` inverts keys and values instantly.

## Common mistake: The Nesting Trap: Unreadable Monster One-Liners

A common trap for developers learning comprehensions is nesting multiple `for` and `if` clauses into a single dense line, such as `[val for row in matrix for val in row if val > 0 and val % 2 == 0]`.

While syntactically valid, deeply nested comprehensions are difficult to read, impossible to step-debug with breakpoints, and violate PEP 20 ('Readability counts').

Rule of thumb: if a comprehension requires more than one `for` clause or more than two lines of code, write an explicit multi-line `for` loop with descriptive variable names instead.

## Tip: Prefer Generator Expressions for Pure Reductions

If you are immediately passing your transformed items into an aggregator like `sum()`, `max()`, `min()`, or `any()`, do not use square brackets `[]`. Use parentheses `()` to create a generator expression: `sum(x**2 for x in nums)`. This streams items one at a time without allocating an intermediate list in memory.

## Try it: Interactive Comprehension Transformation Pipeline

Step through the comprehension transformation conveyor. Toggle between filtering even squares, inverting a key-value dictionary, and contrasting the declarative bytecode path against an imperative append loop.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/list-comprehensions

## Check yourself

### Question 1

What is the result of the comprehension `[x * 2 for x in range(6) if x % 2 == 0]`?

- A. [0, 4, 8]
- B. [0, 2, 4, 6, 8, 10]
- C. [2, 6, 10]
- D. [4, 8]

Correct answer: A

range(6) produces 0, 1, 2, 3, 4, 5. The filter 'if x % 2 == 0' selects 0, 2, and 4. The expression 'x * 2' doubles each selected number, yielding [0, 4, 8].

- Why not B: range(6) produces 0, 1, 2, 3, 4, 5. The condition 'if x % 2 == 0' filters out odd numbers, so 1, 3, and 5 are not included.
- Why not C: 0 % 2 == 0 is true, so 0 * 2 = 0 must be the first element.
- Why not D: 0 is an even number in range(6), so 0 is included.

### Question 2

Where must a conditional expression go if you want to provide a fallback value for elements that fail a check?

- A. Before the 'for' keyword: [expr if cond else alt for item in iterable]
- B. After the iterable: [expr for item in iterable if cond else alt]
- C. Inside an 'else' block following the closing bracket ]
- D. Inside a lambda passed to the iterable

Correct answer: A

When transforming every element with a fallback, use Python's ternary expression before the 'for' loop: '[expr if cond else alt for item in iterable]'. Trailing 'if' without 'else' acts purely as a filter.

- Why not B: Trailing 'if' cannot have an 'else' clause; trailing if acts purely as a filter.
- Why not C: Comprehensions do not support an else block outside their brackets.
- Why not D: Ternary expressions sit directly before 'for'.

### Question 3

Why do list comprehensions execute significantly faster than an equivalent for loop using list.append()?

- A. They utilize specialized C-level LIST_APPEND opcodes that bypass repeated Python attribute lookups and call stack frames
- B. They execute on multiple CPU threads concurrently in parallel
- C. They bypass CPython memory allocation by writing to the stack instead of heap memory
- D. They compile into C extensions using Cython at runtime

Correct answer: A

List comprehensions compile down to the CPython LIST_APPEND bytecode instruction. In contrast, an imperative for loop must repeatedly resolve the .append attribute and create Python function call frames for every element.

- Why not B: Comprehensions execute on the single calling thread in CPython.
- Why not C: Lists are always allocated on the heap in Python.
- Why not D: Standard CPython compiles them to bytecode without Cython.

## Remember this

- Syntax structure: [expression for item in iterable if condition].
- List comprehensions run faster than .append() loops due to direct C-level LIST_APPEND bytecode opcodes.
- Place trailing 'if' to filter elements; place leading 'if-else' to transform every element.
- Dictionary and set comprehensions use curly braces {} with either key:value pairs or single values.
- Never nest multi-tier loops inside one comprehension; prefer clean multi-line for loops.
