Skip to content

25. Flatten Any Iterable Lazily

Difficulty: Medium · Topic: Generators & iterators

Write a generator iflatten(obj) that yields the atoms of any nested structure of iterables (lists, tuples, sets, ranges, generators...) in order, lazily.

Your code runs in CPython on our servers against 6 tests, including hidden ones.

Sample test

list(iflatten([1, (2, [3, "ab"]), range(4, 6), None]))

Expected: [1, 2, 3, 'ab', 4, 5, None]

Hints

Hint 1yield from iflatten(x) hands every item of the recursive call to your caller.
Hint 2Test "is it iterable?" with iter(obj) inside try/except TypeError.
Hint 3A one-character string is an iterable whose only item is itself: without the string check, recursion never ends.

Learn the concepts

More Python problems

All Python problems