As Trey Hunner said: “The yield from
statement is to a list.extend()
the way a yield
statement is to a list.append()
.”
Basic Usage
def my_generator():
yield 1
yield 2
yield from [3, 4, 5]
yield 6
gen = my_generator()
print(list(gen)) # Output: [1, 2, 3, 4, 5, 6]
In this example, yield from [3, 4, 5]
is equivalent to:
Example: Deep-Flattening Nested Iterables
from collections.abc import Iterable
from typing import Any, Iterator
def deep_flatten(iterable: Iterable) -> Iterator[Any]:
"""Flatten an iterable of iterables."""
for element in iterable:
# Handle strings as special case, since they are iterable
if isinstance(element, str):
yield element
# Recursively flatten nested iterables
elif isinstance(element, Iterable):
yield from deep_flatten(element)
# Base case: yield non-iterable elements
else:
yield element