Modifying yielded elements
In the following example, the function squaredNubmers
uses yield from
to create lists with two elements: the first is the number yielded from numbers
while the second one is the number squared:
def numbers():
yield 7
yield 28
yield 12
yield 3
def squaredNubmers():
yield from ( [x, x**2] for x in numbers() )
for i in squaredNubmers():
print(f'{i[0]} -> {i[1]}')
Flattening nested lists
def flatten(listOrElem):
if isinstance(listOrElem, list):
for x in listOrElem:
yield from flatten(x)
else:
yield listOrElem
for i in flatten( [ 1, ['a', 'b', ['I', 'II', 'III', 'IV' ], 'c' ], 2, 3] ):
print(i)