Flatten nested lists with yield from

MediumIterator & Generator Programs · 12 of 20

Write a recursive generator that flattens nested lists.

Advertisement
Output
[1, 2, 3, 4, 5]

Approach

  1. yield from the recursive call for each sub-list.

Solution

Python
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.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment