A generator works like a ticket machine at a stadium: instead of printing all tickets for ten thousand fans at once, it prints one when you ask and waits until you request the next. In Python, this means using
yield inside a function to pause execution and hand back values one at a time.The Mental Model
def count_up(n):
for i in range(1, n + 1):
yield i
g = count_up(3)
print(next(g)) # 1, then pauses at yield
print(next(g)) # 2: carries on from the pause
print(list(g)) # [3]: the rest of the loopNotice that
In
count_up returns a generator object, not the numbers themselves. The code inside does not run until you ask for values by calling next() or looping over it. This is lazy evaluation: work happens only when needed.In
count_up, range(1, n + 1) counts from 1 up to n: a range stops just before its second number, so the + 1 takes it up to n itself. A range can also take a third number, the step: how much to count up by each time. range(10, 40, 10) gives 10, 20 and 30.Why Lazy Evaluation Matters
def temp_readings(n):
# Imagine reading from a slow sensor
for i in range(1, n + 1):
yield 20.5 + (i * 0.1)
total = sum(temp_readings(5))
print(total)The example above added up the readings without ever storing all five at once. That matters for big jobs, such as a log file with millions of lines: a list of every line could use a lot of memory, while a generator holds one line at a time.
Generator Expressions
You can write a one-line generator using round brackets
( ) instead of square brackets [ ]. It looks like a list comprehension, but it makes its values one at a time, when asked. That's handy when you only pass the values on, for example to sum(), and never need the whole list.# Eager: creates [1, 4, 9] in memory
squares_list = [x * x for x in range(1, 4)]
print(squares_list)
# Lazy: produces values one by one on demand
lazy_squares = (x * x for x in range(1, 4))
print(next(lazy_squares)) # Prints 1
print(list(lazy_squares)) # Prints [4, 9]def one_shot():
yield "first"
yield "second"
seq = one_shot()
print(list(seq)) # ['first', 'second']
print(list(seq)) # [] - Empty! It's exhausted.