Editor

Flatten with yield from

Advanced · Write the code · from Python Generators: Process Millions of Items Without Running Out of Memory

From the lesson: What Does yield from Do?

yield from delegates to another iterable, yielding each of its values as if you wrote yield for each one individually. It's especially useful for flattening nested structures or composing generators.

Read this part of the lesson

Write a generator function flatten_deep(data) that flattens a nested list of arbitrary depth. If an element is a list, recurse into it. Otherwise, yield the element.

for item in flatten_deep([1, [2, [3, 4], 5], [6]]):
    print(item)
# Output: 1 2 3 4 5 6
def flatten_deep(data):
# For each item in data:
# If it's a list, recursively yield from flatten_deep
# Otherwise, yield the item
pass
for item in flatten_deep([1, [2, [3, 4], 5], [6]]):
print(item)

More Generator exercises

All Python exercises · 50 practice problems · Advanced Python quiz