Index Ai Academy
Phase 0 · ToolsPython core

Comprehensions

About 25 minLooking ahead: some prerequisites aren't done yet

Why this matters

Most data work is "take this collection and give me a cleaned, filtered or changed version of it". Comprehensions say that in one line. AI code is full of them: tidying documents before they're embedded, picking out the messages with a given role, building a lookup table of scores. Even when an assistant writes the code, you need to read these lines fluently to know what they do.

  • Build a new list from an existing one with a list comprehension
  • Keep only some items with an if clause
  • Loop over a dictionary's keys, values, or both with .items()
  • Build a dictionary with a dict comprehension
  • Decide when a plain loop is clearer than a comprehension

The loop you keep writing

You've written this pattern already: start an empty list, loop over another list, append a changed version of each item.

emails = ["Ana@Shop.com", "BEN@mail.com", "cara@site.io"]

clean = []
for e in emails:
    clean.append(e.lower())

print(clean)

Picture asking a helper to lowercase a list of emails. You wouldn't say "take the first one, lowercase it, write it down, now take the second one". You'd say "lowercase every email on this list". A list comprehension is that one-sentence instruction:

emails = ["Ana@Shop.com", "BEN@mail.com", "cara@site.io"]
clean = [e.lower() for e in emails]
print(clean)

Read it left to right as "e.lower(), for each e in emails". The general shape is:

[expression for item in collection]

The square brackets say you're building a list. The for ... in ... part is the same loop you already know. The expression at the front is what goes into the new list for each item. The original list is left unchanged.

prices = [28, 64, 18, 22, 26]
with_tax = [round(p * 1.2, 2) for p in prices]
print(with_tax)
print(prices)