Loading lessons...
Generators
Generators
A generator produces a sequence of values one at a time, pausing between each one. It never stores the whole list in memory.
A simple generator
Use yield instead of return:
def countdown(n):
while n > 0:
yield n
n -= 1
for num in countdown(3):
print(num)
# 3, 2, 1
yield vs return
returngives one value and the function is done.yieldgives a value, then PAUSES. The next call continues right after the yield.
Generator objects
Calling a generator function gives you a generator object, not the values:
gen = countdown(3)
print(next(gen)) # 3
print(next(gen)) # 2
next() steps through
next(gen) runs the generator up to the next yield. When it's empty, it raises StopIteration.
Generator expressions
Like list comprehensions but with parentheses:
squares = (x * x for x in range(1000000)) # tiny memory
A list of a million items would use lots of memory; the generator uses almost none.
Why generators?
- Huge or infinite sequences without using memory.
- Lazily produce values only when needed.
- Great for streaming data, reading big files.
TL;DR
yieldmakes a function a generator.- Generators pause and resume between values.
next()pulls each value; StopIteration ends them.- Use them for big or infinite sequences.