Browse topics

Generators and yield

Version
3.14
Review
Draft

Summary#

A function containing yield returns a generator when called. The generator produces values on demand and keeps its local state between them. yield from delegates to another iterable.

Syntax#

python
def produce():
    yield value
    yield from iterable

lazy = (expression for item in iterable)

Example#

python
def batches(items, size):
    print("started")
    for start in range(0, len(items), size):
        yield items[start:start + size]


def chained():
    yield from "ab"
    yield from (number * number for number in range(3))


pending = batches([1, 2, 3, 4, 5], 2)
print("created")
print(next(pending))
print(list(pending))
print(list(pending))
print(list(chained()))

Expected output#

Text
created
started
[1, 2]
[[3, 4], [5]]
[]
['a', 'b', 0, 1, 4]

Common mistakes#

Calling a generator function binds its arguments immediately. Its body, including any validation inside it, waits until the generator first resumes. A generator expression evaluates its leftmost iterable immediately. Create a fresh generator or save its values when you need to iterate again.

Version applicability#

Generator functions and generator expressions work on all Python 3 releases. yield from requires Python 3.3 or later, as does the example. Since 3.8, yield is prohibited in the implicit scope of comprehensions and generator expressions.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0