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.
- Strings and bytes are atoms: yield them whole. So is anything that is not iterable, such as a number or
None. - Inner iterables may be endless, so yield each atom as soon as you reach it.
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 1
yield from iflatten(x) hands every item of the recursive call to your caller.Hint 2
Test "is it iterable?" withiter(obj) inside try/except TypeError.Hint 3
A one-character string is an iterable whose only item is itself: without the string check, recursion never ends.Learn the concepts
- Iterators, yield from and itertools · 8 min read. The iterator protocol, re-iterable classes, recursive generators and the itertools you will use.
More Python problems
- Read a File in Chunks · Easy
- Batch an Iterable · Easy
- A Generator Pipeline · Medium
- Moving Average over a Stream · Medium
- A Re-iterable Date Range · Medium
- Merge Sorted Streams Lazily · Hard