hayaliv

hayaliv / Hi! Python / Level 0

Comprehensions

A comprehension builds a list, dict or set from another collection in one short line.

Hi! Python · Level 0: Python core · Checked against the Python 3.12 documentation · Updated 2026-10-17

Think of it like this

A comprehension is like a sandwich-making line. Bread slides along, a worker skips bread that fails a check, and each good slice comes out as a finished sandwich on the other side.

Where the analogy stops being true. A sandwich line makes one sandwich per slice. A set or dict comprehension can end up with fewer items, because duplicate values or keys collapse.

What to know

Example

replies = [("r1", "meeting_request"), ("r2", "not_interested"), ("r3", "meeting_request"), ("r4", "question")]
meetings = [rid for rid, lab in replies if lab == "meeting_request"]
print(meetings)
labels = {lab for rid, lab in replies}
print(sorted(labels))
sizes = {lab: len(lab) for lab in sorted(labels) if lab != "question"}
print(sizes)
loop_result = []
for rid, lab in replies:
    if lab == "meeting_request":
        loop_result.append(rid)
print(loop_result == meetings)

It prints:

['r1', 'r3']
['meeting_request', 'not_interested', 'question']
{'meeting_request': 15, 'not_interested': 14}
True

Predict, then check

1. What does this print?

print([n * n for n in range(4)])
Show the answer
[0, 1, 4, 9]

For each n from 0 to 3 the expression n * n is added to the new list.

2. What does this print?

print({w: len(w) for w in ["yes", "no"]})
Show the answer
{'yes': 3, 'no': 2}

A dict comprehension builds key: value pairs, here each word with its length.

3. What does this print?

print({len(w) for w in ["aa", "bb", "c"]})
Show the answer
{1, 2}

The lengths are 2, 2 and 1. A set keeps each distinct value once.

Try it

Write keep_confident(scores, threshold) that takes a dict of label to score and returns a new dict with only the labels whose score is at least threshold. Use a dict comprehension.

def keep_confident(scores, threshold):
    return {}
Show a solution
def keep_confident(scores, threshold):
    return {k: v for k, v in scores.items() if v >= threshold}

Common mistake

A good habit is to avoid cramming many conditions into one comprehension. If you have to read it twice, write the loop instead.

In a small-language-model project

In a fine-tuning project you usually use comprehensions to filter examples by label or to build a label-to-id dict, and plain loops when a step needs logging or several actions.

Sources

Each quote below appears word for word on the cited page of the official Python documentation (version 3.12).

Step through this lesson in the Hi! Python desktop

← FunctionsText and the `with` statement →