Generator expressions
A generator expression is like a list comprehension in parentheses that produces values one at a time, without building a list.
Used in 111 lessons of the course, from 00.01.
A generator expression is written (expr for x in iterable if cond). You read it like a list comprehension: "expr for each x in iterable, if cond". The difference is that it doesn't build a list. It creates a generator that hands out each value when something asks for it.
Why write it this way? Because often you only pass the values on to another function, like sum(), sorted(), any() or "".join(). You don't need to keep an intermediate list in memory.
When it's the only argument of a function, you can drop the extra parentheses. That's why the course writes:
sorted(t for t, (d, _) in GLOSSARY.items() if word in t)
Here sorted() receives the generator and returns a sorted list.
Watch out: a generator is consumed only once. After you loop over it, it's empty.
Reach for it when: you're feeding values straight into a function like `sum()`, `sorted()`, `any()` or `join()` and don't need to keep the list.
Examples
Common mistake
squares = (n * n for n in [1, 2, 3]) print(sum(squares)) print(sum(squares))
Why: A generator is consumed only once. The second time it has no values left.
How to write it: If you need the values more than once, use a list comprehension with square brackets.
Common mistake
names = (n.upper() for n in ["ana", "luis"]) print(names[0])
Why: A generator isn't a list: it doesn't support indexing.
How to write it: Use [n.upper() for n in ...] if you need indexes, or next(names) for the first one.
