Python Practice › Iterator & Generator Programs › Program 12
Flatten nested lists with yield from
Write a recursive generator that flattens nested lists.
Output
[1, 2, 3, 4, 5]
Approach
yield fromthe recursive call for each sub-list.
Solution
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]]], 5])))Output
[1, 2, 3, 4, 5]
Learn the concept
New to this topic? Read the lesson, then come back.