The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Transform into a list | squares = [n * n for n in numbers] | View examples |
| Filter and transform | names = [user.name for user in users if user.active] | View examples |
| Build a dictionary | by_id = {user.id: user for user in users} | View examples |
| Build unique results | domains = {email.rsplit('@', 1)[-1] for email in emails} | View examples |
| Stream transformed values | total = sum(n * n for n in numbers) | View examples |
| Pair with counters | for line_number, line in enumerate(lines, start=1): handle(line_number, line) | View examples |
| Pair equal-length inputs | for name, score in zip(names, scores, strict=True): report(name, score) | View examples |
| Sort by a key | ordered = sorted(users, key=lambda user: user.name.casefold()) | View examples |
| Flatten one level | flat = [item for group in groups for item in group] | View examples |
| Group adjacent keys | for key, group in groupby(sorted(rows, key=key_fn), key=key_fn): consume(key, group) | View examples |
| Chain iterables lazily | for item in chain(first, second): consume(item) | View examples |
| Detect no break | for ... else ... | View examples |
Comprehensions are concise expressions for simple transformations and filters; ordinary loops are clearer when state, branching, logging, or error handling dominates. Generator expressions stream values, and built-in iteration tools preserve intent without manual indexes or temporary collections.
Step by step
Detailed examples
Keep one transformation and one clear filter
A comprehension executes its clauses in nested left-to-right order and has its own implicit scope. Use it when the result construction is the whole idea. Switch to a loop when expressions need side effects, multiple state updates, exception handling, or dense conditional logic.
records = [(' Ada ', True), ('Lin', False), (' Grace ', True)]
names = [name.strip() for name, active in records if active]
length_by_name = {name: len(name) for name in names}
print(names)
print(length_by_name) ['Ada', 'Grace']
{'Ada': 3, 'Grace': 5}Stream when a consumer accepts an iterable
Generator expressions calculate values on demand and are single-use. They reduce peak memory for large pipelines but do not make the source replayable. Parentheses can be omitted when the generator is the sole function argument.
numbers = range(1, 6)
print(sum(n * n for n in numbers))
print(any(n > 4 for n in numbers)) 55
TrueUse built-ins instead of manual position state
enumerate produces counters and values. zip truncates silently by default; strict=True converts a data-shape mismatch into an error. sorted returns a stable list, so equal keys preserve original order; compute expensive sort keys once if necessary.
names = ['Ada', 'lin', 'Grace']
scores = [98, 91, 95]
pairs = list(zip(names, scores, strict=True))
for rank, (name, score) in enumerate(sorted(pairs, key=lambda pair: pair[1], reverse=True), 1):
print(rank, name, score) 1 Ada 98
2 Grace 95
3 lin 91Make nested cardinality visible
Nested comprehension clauses multiply iterations and can become hard to read. itertools.chain flattens one level lazily. groupby groups adjacent equal keys rather than all equal values globally, so sort using the same key unless input is already grouped.
from itertools import chain, groupby
groups = [[1, 2], [3], [4, 5]]
print(list(chain.from_iterable(groups)))
rows = [('a', 1), ('b', 2), ('a', 3)]
for key, items in groupby(sorted(rows), key=lambda row: row[0]):
print(key, [value for _, value in items]) [1, 2, 3, 4, 5]
a [1, 3]
b [2]Use loop else for search completion
break exits the nearest loop; continue advances to its next iteration. A loop's else suite runs only when iteration exhausts normally, not after break. This can express search failure without a flag, but a helper returning early is often clearer for complex searches.
number = 17
for candidate in range(2, number):
if number % candidate == 0:
print('factor', candidate)
break
else:
print('prime') primeLocal code tester
Practice iteration pipelines
Transform, filter, sort, enumerate, and lazily flatten sample data.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



