Interview question
How do you chain multiple generators together, and what is yield from used for? Multiple generators को साथ में कैसे chain करें, और yield from किस लिए है?
Answer
yield from delegates iteration to a sub-generator or iterable, simplifying the common pattern of a generator that yields all values from another one.
# WITHOUT yield from - manual delegation with a loop
def inner_gen():
yield 1
yield 2
yield 3
def outer_gen_manual():
for value in inner_gen():
yield value # verbose way to delegate
# WITH yield from - concise delegation
def outer_gen():
yield from inner_gen() # equivalent to the manual loop above
print(list(outer_gen())) # [1, 2, 3]
# Combining multiple generators/iterables
def combined():
yield from range(3) # 0, 1, 2
yield from ['a', 'b'] # 'a', 'b'
yield from (10, 20) # 10, 20
print(list(combined())) # [0, 1, 2, 'a', 'b', 10, 20]
# Practical use: flattening nested structures with recursion
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item) # recursively delegate to sub-lists
else:
yield item
nested_list = [1, [2, 3, [4, 5]], 6, [7, [8, 9]]]
print(list(flatten(nested_list))) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Chaining generators with itertools.chain (alternative approach)
from itertools import chain
gen1 = (x for x in range(3))
gen2 = (x for x in range(10, 13))
combined_chain = chain(gen1, gen2)
print(list(combined_chain)) # [0, 1, 2, 10, 11, 12]yield from iteration को किसी sub-generator या iterable को delegate करता है, एक generator से दूसरे की सभी values yield करने के common pattern को सरल बनाता है।
# yield from के बिना - manual loop से delegation
def inner_gen():
yield 1
yield 2
yield 3
def outer_gen_manual():
for value in inner_gen():
yield value
# yield from के साथ - concise
def outer_gen():
yield from inner_gen()
print(list(outer_gen())) # [1, 2, 3]
# Multiple generators/iterables combine करना
def combined():
yield from range(3)
yield from ['a', 'b']
yield from (10, 20)
print(list(combined())) # [0, 1, 2, 'a', 'b', 10, 20]
# Nested structures flatten करना recursion से
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
nested_list = [1, [2, 3, [4, 5]], 6, [7, [8, 9]]]
print(list(flatten(nested_list))) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# itertools.chain से generators chain करना
from itertools import chain
gen1 = (x for x in range(3))
gen2 = (x for x in range(10, 13))
combined_chain = chain(gen1, gen2)
print(list(combined_chain)) # [0, 1, 2, 10, 11, 12]Was this answer clear?