Python 3.3+Iterators & generatorsterm
yield from
generators
Delegates yielding to another generator or iterable. It simplifies nested generators.
Syntax
yield from iterable
It is more than shorthand for a for loop with yield: yield from forwards send() and throw() into the subgenerator, and whatever the subgenerator returns becomes the value of the yield from expression itself. For plain iteration the savings are cosmetic; the real payoff is coroutines and recursive traversal (trees, nested lists), which is why Python 3.3 introduced it.
Examples
def chain(*iterables):
for it in iterables:
yield from it
print(list(chain([1,2],[3,4],[5]))) # → [1,2,3,4,5]
def flatten(lst):
for item in lst:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1,[2,[3,4]],5]))) # → [1,2,3,4,5]
def gen_a():
yield 1; yield 2
def gen_b():
yield from gen_a()
yield 3
print(list(gen_b())) # → [1,2,3]
# yield from с range
def gen_range(n):
yield from range(n)
print(list(gen_range(5))) # → [0,1,2,3,4]
# yield from возвращает значение (return в под-генераторе)
def sub():
yield 1; yield 2
return 'done'
def main():
result = yield from sub()
print('sub returned:', result) # → done
list(main()) # → [1,2]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy