Comprehensions
Filter a scorecard with a four-line loop, then with a one-line list comprehension, and meet the dict and set versions.
A very common pattern is: start with an empty list, loop over some items, keep the ones that pass a test, and append a transformed version of each. Python has a one-line form for exactly that, called a list comprehension: [name for name, runs in scores.items() if runs >= 50]. It reads as “collect name, for each pair, if the test holds”. The result is an ordinary list.
The same idea works for the other collections. Braces with a key: value pair before the for make a dict comprehension. Braces without a colon make a set comprehension. The for and if parts appear in the same order they would in the loop version, which is the trick for reading a long one: find the for, then the if, then the expression at the front.
Press Run on the loop version first, and watch fifties build up one append at a time. Then switch the Try it selector to the comprehension version and see the same result appear in one step.
# Pick out the fifties from a scorecard, two ways.
scores = {"Rohit": 83, "Virat": 12, "Gill": 57, "Rahul": 40}
# Loop version
fifties = []
for name, runs in scores.items():
if runs >= 50:
fifties.append(name)
print(fifties)
# Comprehension version: same result, one line
fifties = [name for name, runs in scores.items() if runs >= 50]
print(fifties)
# Dict comprehension: match fee bonus of Rs 10 per run
bonus = {name: runs * 10 for name, runs in scores.items()}
print(bonus)
# Set comprehension: unique first letters, duplicates dropped
initials = {name[0] for name in scores}
print(sorted(initials))Press Play to run the program line by line, or step with ← →.
Variables
Nothing defined yet.
Output
Nothing printed yet.
What to notice
- A comprehension is a loop in a different shape. Expression first, then
for item in iterable, then an optionalif. The loop version needs an empty list and anappend; the comprehension does both for you. - The loop variable stays inside.
nameandrunsfrom the comprehension do not exist afterwards, which is why they never appeared in the Variables panel. The loop version leaves them behind. - Dict and set versions differ by one colon.
{name: runs * 10 for ...}makes a dict;{name[0] for ...}makes a set. A set drops duplicates for free. - Looping over a dict gives keys.
for name in scoresyields"Rohit","Virat"and so on. Use.items()when you need the values too. - Keep it to one line you can read aloud. Two nested
forclauses or a longifare a sign to go back to a plain loop. Readability is the whole point.
Why this matters for AI work
Comprehensions are how you reshape data between steps of an agent. Pick the names out of a list of search results: [r["title"] for r in results]. Keep the test cases that failed: [c for c in cases if not c["passed"]]. Turn a list of tool results into a lookup by city: {r["city"]: r for r in reports}. One line each, and anyone who has seen this lesson can read them.