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 lessonWrite 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 6def 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
- Your First GeneratorIntermediate
- Predict the Generator OutputIntermediate
- Refactor to a GeneratorIntermediate
- Build a Data PipelineAdvanced
- Fix the Generator BugAdvanced
- Infinite Fibonacci GeneratorAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz