hayaliv / Hi! Python / Level 0
Comprehensions
A comprehension builds a list, dict or set from another collection in one short line.
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
- A list comprehension builds a new list from another iterable.
- An if at the end keeps only the items that pass the condition.
- A dict comprehension builds a dict from key and value expressions.
- A set comprehension builds a set, so duplicates collapse.
- A good habit is to switch to a plain for loop when you need several steps, several conditions or a running total.
- Comprehensions give the same result as the loop version in the example output.
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).
List comprehensions provide a concise way to create lists.
docs.python.org/3.12/tutorial/datastructures.html — List comprehensions give a concise way to create lists.or to create a subsequence of those elements that satisfy a certain condition.
docs.python.org/3.12/tutorial/datastructures.html — A comprehension can create a subsequence of elements that satisfy a condition.dict comprehensions can be used to create dictionaries from arbitrary key and value expressions
docs.python.org/3.12/tutorial/datastructures.html — Dict comprehensions use key and value expressions.Similarly to list comprehensions , set comprehensions are also supported
docs.python.org/3.12/tutorial/datastructures.html — Set comprehensions are supported.