Learning navigation

Code with Animation

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.

Python7 min readConcept 22 of 24

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.

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.

Select Comprehension Pipeline:
# 1. Source numbers:
nums = [1, 2, 3, 4, 5, 6]
# 2. Filter evens & square:
evens = [x**2 for x in nums if x % 2 == 0]
# Result: [4, 16, 36]
DECLARATIVE COMPREHENSION PIPELINE1. ITERABLEnums = [1..6]Stream items2. FILTER [if]x % 2 == 0Drop 1,3,5 | Keep 2,4,63. EXPR [x**2][4, 16, 36]C-speed listEXECUTION STREAM:1 ➔ Rejected | 2 ➔ 2**2 = 4 | 3 ➔ Rejected | 4 ➔ 16 | 6 ➔ 36STREAM PIPELINE: Filter drops odds, projects even squares✓ [x**2 for x in nums if x % 2 == 0] -> [4, 16, 36]
★ Python Rule: Keep comprehensions readable. If a comprehension requires multiple nested for clauses or exceeds two lines, rewrite it as an explicit multi-line for loop to uphold PEP 20.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the result of the comprehension `[x * 2 for x in range(6) if x % 2 == 0]`?
  2. 2Where must a conditional expression go if you want to provide a fallback value for elements that fail a check?
  3. 3Why do list comprehensions execute significantly faster than an equivalent for loop using list.append()?

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.

Done with this concept?

Mark it complete to track your progress. No login needed.