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.
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.
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.
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.