Flatten It (generator)

mediumpy_functional

Implement flat_it(sequence) as a generator that lazily flattens an iterable with an arbitrary level of nesting into a flat stream of leaves, in order. For example list(flat_it((1, (2, 3), [4, [5, 6], 7]))) == [1, 2, 3, 4, 5, 6, 7].

Strings are iterable, so a multi-character string flattens into its characters ("ab""a", "b"); stop recursing at a single character so iterating a 1-char string terminates. Non-iterables are yielded as-is. Use yield (the result must be a generator).

Your solution

Edit flat_it and run the real pytest suite in your browser — no install required. Your code is saved locally.

⌘/Ctrl + ↵

Loading the Python runtime (first run only)…

Hints

Hint 1

Iterate the sequence; if an item is iterable, `yield from flat_it(item)`, else `yield item`.

Hint 2

Treat strings carefully: a string is iterable, so stop recursing once you reach a single character.