Comprehensions

Filter a scorecard with a four-line loop, then with a one-line list comprehension, and meet the dict and set versions.

7 min Free

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.

Ready
# 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 ← →.

00/10

Variables

Nothing defined yet.

Output

Nothing printed yet.

What to notice

  1. A comprehension is a loop in a different shape. Expression first, then for item in iterable, then an optional if. The loop version needs an empty list and an append; the comprehension does both for you.
  2. The loop variable stays inside. name and runs from the comprehension do not exist afterwards, which is why they never appeared in the Variables panel. The loop version leaves them behind.
  3. 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.
  4. Looping over a dict gives keys. for name in scores yields "Rohit", "Virat" and so on. Use .items() when you need the values too.
  5. Keep it to one line you can read aloud. Two nested for clauses or a long if are 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.

Check your understanding

1. What is [x * 2 for x in [1, 2, 3] if x > 1]?
2. Which expression builds a set?
3. What does the loop version need that the comprehension does not?