Phase 0 · Tools · Python core
Comprehensions
Filter and transform a whole collection in one readable line.
Why it matters
Most data work is "take this collection and give me a cleaned, filtered or transformed version of it". Comprehensions say that in one line, and AI code is full of them: stripping whitespace from 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.
What you'll be able to 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
Before this lesson
Next in this phase: Errors and exceptions