yield (generators)
yield turns a function into a generator that hands out values one at a time, pausing between them, instead of building a whole list.
def generator():
yield value
yield from iterableA function that contains yield is a generator function. Calling it does not run the body; it returns a generator object. Each time a loop asks for the next value, the body runs until the next yield, hands that value out, and pauses right there.
Because values are made on demand, a generator uses almost no memory, even for millions of items or an endless stream. It is ideal for reading big files line by line or producing sequences you only need once.
A generator can be walked through only once. After it is used up, looping over it again gives nothing. Call the function again to get a fresh one.
Return value
Calling the function returns a generator object; each yield produces one value of it.
Examples
1A first generator
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print(x)
print(list(countdown(5)))3 2 1 [5, 4, 3, 2, 1]
2It pauses between values
def steps():
print("start")
yield 1
print("middle")
yield 2
g = steps()
print("got", next(g))
print("got", next(g))start got 1 middle got 2
Nothing runs until next() asks for a value; then the body runs only up to the next yield.
3Read only the lines you need
def valid_rows(lines):
for line in lines:
line = line.strip()
if line and not line.startswith("#"):
yield line.split(",")
with open("sales.csv", encoding="utf-8") as f:
for name, amount in valid_rows(f):
print(name, float(amount))Oslo 120.5 Lima 80.0
4An endless generator
An infinite loop is fine in a generator, because it only runs as far as you ask.
def invoice_numbers(start):
n = start
while True:
yield f"INV-{n:04d}"
n += 1
numbers = invoice_numbers(41)
for _ in range(3):
print(next(numbers))INV-0041 INV-0042 INV-0043
5yield from and generator expressions
def all_items(*lists):
for lst in lists:
yield from lst
print(list(all_items([1, 2], [3], [4, 5])))
total = sum(x * x for x in range(1, 4))
print(total)[1, 2, 3, 4, 5] 14
(x * x for x in ...) is a generator expression: a one-line generator, like a list comprehension in round brackets.
Common mistakes
Using a generator twice
A generator is used up after one pass. The second loop gets nothing.
squares = (n * n for n in range(4))
print(list(squares))
print(list(squares))[0, 1, 4, 9] []
Expecting a list
Printing a generator shows <generator object ...>, not the values, and len() does not work on it. Wrap it in list() when you need all values at once.
Questions people ask
What is the difference between yield and return?
return ends the function and gives one result. yield gives a value and pauses, so the function can produce many values over time.
When should I use a generator?
When the data is large, endless, or you only need to go through it once. For small results you reuse, a list is simpler.
How do I get the next value by hand?
next(gen). When the generator is finished, next() raises StopIteration; next(gen, default) returns the default instead.