List Comprehensions
py-list-comprehensions
Code Snippets
Python List Comprehension Cheat Sheet
List comprehensions are Python's most distinctive feature: they pack filter, map, and flatten into a single expression. This cheat sheet covers the basic map-and-filter form, the nested form for cartesian products and matrix flattening, and the conditional-expression form that branches inside the output. Each pattern shows up many times per Python file in real codebases.
Python Dict Comprehension Cheat Sheet
Dict comprehensions build mappings without explicit loops, the same way list comprehensions build lists. They are the right tool for inverting a dict, projecting a list of tuples into a key-value map, and filtering an existing dict by predicate. This snippet covers the basic build form, the invert and merge patterns, and the filtering form for trimming an existing dict.
Python Set Comprehension Patterns
Set comprehensions are the underused sibling of list and dict comprehensions. They build deduplicated collections in one line and excel at unique-by-key extraction, set algebra, and quick membership filters. This snippet covers the basic uniqueness pattern, the unique-by-projection form for objects, and set algebra (intersection, difference) expressed as comprehensions.
Quick Sort One-Liner in Python
The functional Quicksort one-liner in Python is a classic teaching artifact: it is short enough to fit on one line and shows comprehensions plus recursion working together. This snippet covers the three-way functional one-liner, an in-place Lomuto-partition variant for performance, and a benchmark contrast against `sorted` to show why the one-liner is for teaching, not production.
Community
When I Stop Reaching for List Comprehensions
I love comprehensions, but I have learned the three cases where they cost more than they save: nested filtering, side effects, and big intermediate lists. Here is the pattern I switch to in each.
List Comprehensions and When to Stop Using Them
Comprehensions are the fastest way to express a simple transform-and-filter, but they decay into write-only code the moment you nest them or sneak side effects in. Here is the line I draw.
