What does yield from do in Python?
yield from iterable hands over each item of another iterable or generator to the caller, as if you had written a for loop with yield. It also passes through values sent into the generator and returns the sub-generator's return value.
Explain it simply
A relay race coach does not run the leg himself; he passes the baton to another runner and lets that runner's laps count as his own team's laps. yield from is that handover: the caller receives items straight from the inner generator.
Example
def first_years():
yield "Asha"
yield "Dev"
def second_years():
yield "Ira"
def all_students():
yield from first_years()
yield from second_years()
print(list(all_students())) # Output: ['Asha', 'Dev', 'Ira']
def inner():
yield 1
return "done"
def outer():
result = yield from inner()
yield result
print(list(outer())) # Output: [1, 'done']
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3]], 4]))) # Output: [1, 2, 3, 4]What to say in the interview
"yield from delegates to a sub-iterator: items flow straight through to the caller. It replaces a for loop with yield, forwards send() and throw() properly, and captures the sub-generator's return value. It makes recursive generators, like walking a tree or flattening a list, very clean."