The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Transform into a listsquares = [n * n for n in numbers]View examples
Filter and transformnames = [user.name for user in users if user.active]View examples
Build a dictionaryby_id = {user.id: user for user in users}View examples
Build unique resultsdomains = {email.rsplit('@', 1)[-1] for email in emails}View examples
Stream transformed valuestotal = sum(n * n for n in numbers)View examples
Pair with countersfor line_number, line in enumerate(lines, start=1): handle(line_number, line)View examples
Pair equal-length inputsfor name, score in zip(names, scores, strict=True): report(name, score)View examples
Sort by a keyordered = sorted(users, key=lambda user: user.name.casefold())View examples
Flatten one levelflat = [item for group in groups for item in group]View examples
Group adjacent keysfor key, group in groupby(sorted(rows, key=key_fn), key=key_fn): consume(key, group)View examples
Chain iterables lazilyfor item in chain(first, second): consume(item)View examples
Detect no breakfor ... 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

01

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.

Normalize active labels
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)
Output
['Ada', 'Grace']
{'Ada': 3, 'Grace': 5}
Back to quick reference ↑
02

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.

Short-circuit and aggregate lazily
numbers = range(1, 6)
print(sum(n * n for n in numbers))
print(any(n > 4 for n in numbers))
Output
55
True
Back to quick reference ↑
03

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

Pair and rank parallel data
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)
Output
1 Ada 98
2 Grace 95
3 lin 91
Back to quick reference ↑
04

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

Flatten and group values
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])
Output
[1, 2, 3, 4, 5]
a [1, 3]
b [2]
Back to quick reference ↑
05

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.

Find a factor without a flag
number = 17
for candidate in range(2, number):
    if number % candidate == 0:
        print('factor', candidate)
        break
else:
    print('prime')
Output
prime
Back to quick reference ↑

Local code tester

Practice iteration pipelines

Transform, filter, sort, enumerate, and lazily flatten sample data.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software FoundationPython Reference: Displays for lists, sets and dictionariesdocs.python.org
  2. Python Software FoundationPython Tutorial: Looping Techniquesdocs.python.org
  3. Python Software Foundationitertools — Functions creating iteratorsdocs.python.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback