Tags

List Comprehensions

List Comprehensions

0 lessons
4 code snippets
2 community items

py-list-comprehensions

Code Snippets

4 snippets
Code Snippet

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
py-list-comprehensions
py-comprehensions
code-template
cheat-sheet

451

11

Easy
Code Snippet

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
py-comprehensions
py-list-comprehensions
code-template
cheat-sheet

1.1k

15

Easy
Code Snippet

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.

Python
py-comprehensions
py-list-comprehensions
code-template
cheat-sheet

1k

20

Easy
Code Snippet

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.

Python
algorithms
sorting
recursion
py-list-comprehensions

659

7

Medium