Sub topic 7
Generator expressions
This chapter assumes you can write list comprehensions, know that a generator function uses yield, and understand that next() raises StopIteration when an iterator is finished.
What a generator expression is
A generator expression has the syntax of a list comprehension, but it uses parentheses instead of square brackets. It produces a generator object that computes each value only when something asks for it.
squares_list = [x * x for x in range(5)] # builds all five values now
squares_gen = (x * x for x in range(5)) # builds nothing yet
print(squares_list) # [0, 1, 4, 9, 16]
print(squares_gen) # <generator object <genexpr> at 0x...>
print(next(squares_gen)) # 0
print(next(squares_gen)) # 1A generator expression is shorthand for a small generator function. It is the right tool when the logic fits in one expression and you do not need a named function.
def _squares():
for x in range(5):
yield x * xSyntax
The full form is (expression for item in iterable if condition). The if clause is optional, and you can add more for clauses.
words = ["apple", "", "kiwi", "fig"]
lengths = (len(w) for w in words if w)
print(list(lengths)) # [5, 4, 3]When the generator expression is the only argument of a call, you can drop its own parentheses. This is the most common way to use one.
total = sum(x * x for x in range(1000))
longest = max(len(w) for w in ["a", "abc", "ab"])
has_empty = any(not w for w in ["a", "", "b"])
print(total, longest, has_empty) # 332833500 3 TrueIf the call has other arguments, you must keep the parentheses: sorted((x for x in data), reverse=True).
Why use one
sum, max, any, all and "".join read their input once from start to finish. They do not need a list. A generator expression feeds them one value at a time, so the full sequence is never stored.
import sys
big_list = [n for n in range(1_000_000)]
big_gen = (n for n in range(1_000_000))
print(sys.getsizeof(big_list)) # several megabytes
print(sys.getsizeof(big_gen)) # a couple of hundred bytesThe generator's size stays the same however many values it will produce. any and all also stop early, so any(x > 10 for x in huge) stops at the first match.
Common errors
Single use. A generator expression is an iterator, so a second pass finds it empty.
squares = (x * x for x in range(3))
print(list(squares)) # [0, 1, 4]
print(list(squares)) # []If you need several passes, build a list or tuple instead, or create the generator again.
Evaluation timing. Python evaluates the outermost iterable immediately, when the expression is created. Everything else is evaluated later, on each next().
data = [1, 2, 3]
n = 2
gen = (x * n for x in data)
data = [10, 20] # no effect, gen already holds the original list
n = 10 # takes effect, n is looked up on each step
print(list(gen)) # [10, 20, 30]Late errors. Because nothing runs at creation, a bug in the body appears only when you consume the generator, possibly far from the line that created it. A list comprehension fails at once.
Wrong tool for small data. For a short list you will use repeatedly, a list comprehension is clearer and often faster. Choose a generator expression when the data is large, unbounded, or consumed once.
Exercise
What do the two print calls output? g = (x for x in range(3)) print(sum(g)) print(sum(g))
Show answer
The first call prints 3, because 0 + 1 + 2 = 3. The second call prints 0. The first sum exhausted the generator, so the second one sees no values and returns the starting value 0.