Skip to content
Python Basics: Building Collections with Comprehensions

Python Basics: Building Collections with Comprehensions

October 18, 2026

A comprehension builds a new collection from an iterable. It is useful when the task is a short transformation, a filter, or both. These examples clean labels, build a lookup table, and flatten a small collection without modifying the input.

These three standalone examples were tested on Linux with Python 3.12.14. They require no third-party packages. Assertions check the demonstrated results; run the commands normally, without Python’s -O option.

Prepare a scratch directory

You need Bash, a text editor, Python 3 on your PATH, and the mktemp, rm, and rmdir utilities. Keep using the same terminal. Save each named source file as UTF-8. The setup stops the shell if creating or entering the scratch directory fails.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

1. Clean and filter labels

Save this as clean_labels.py:

raw = ["  apple ", "", " PEAR", "   ", "plum"]
labels = [value.strip().lower() for value in raw if value.strip()]
assert labels == ["apple", "pear", "plum"]
assert raw[0] == "  apple "
print(labels)
print(f"Original first value: {raw[0]!r}")

Run it:

python3 clean_labels.py

Output:

['apple', 'pear', 'plum']
Original first value: '  apple '

Read this as “produce a cleaned value for each original value that passes the condition.” The condition tests the original value before the output expression runs. Whitespace-only strings are excluded. The source list remains unchanged; the result is a separate list.

2. Build an index with a dictionary comprehension

Save this as index_products.py:

products = [("A12", "Notebook"), ("B05", "Pencil"), ("A12", "Sketchbook")]
by_code = {code: name for code, name in products}
assert by_code == {"A12": "Sketchbook", "B05": "Pencil"}
print(by_code)
print(f"A12: {by_code['A12']}")

Run it:

python3 index_products.py

Output:

{'A12': 'Sketchbook', 'B05': 'Pencil'}
A12: Sketchbook

A dictionary comprehension uses a key and a value separated by a colon. Repeated keys replace earlier values, as the two A12 records demonstrate. If duplicate codes indicate bad input, validate them with an explicit loop instead of silently accepting the last record.

3. Flatten one level of grouped values

Save this as flatten_groups.py:

groups = [["draft", "review"], [], ["publish"]]
steps = [step for group in groups for step in group]
assert steps == ["draft", "review", "publish"]
assert groups == [["draft", "review"], [], ["publish"]]
print(steps)
print(f"Step count: {len(steps)}")

Run it:

python3 flatten_groups.py

Output:

['draft', 'review', 'publish']
Step count: 3

The clauses follow the same order as nested loops: visit a group, then visit its steps. Empty groups contribute nothing. This flattens exactly one level, not an arbitrarily nested structure. Keep nested comprehensions short enough that this order is obvious.

When to use this

Use a normal loop when you need several statements, detailed error handling, or side effects. A comprehension is best when its purpose is the resulting collection. Lists are built eagerly, so the whole result occupies memory. See the official list comprehension tutorial and dictionary examples.

Clean up

In the same terminal, remove only the three example files, return to your original directory, and remove the empty scratch directory:

rm -- clean_labels.py index_products.py flatten_groups.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on