Flatten Deeply with yield from

Hard ⏱ 18 min 38% acceptance ★★★★★ 4.8
Write the generator deep_flatten(nested) yielding every non-list element from arbitrarily nested lists, delegating recursion with <code>yield from</code> — the statement built precisely for generators calling generators.

Examples

Example 1
Input
list(deep_flatten([1, [2, [3, [4]]], 5]))
Output
[1, 2, 3, 4, 5]
Explanation

Every nesting level unwinds lazily.

Constraints

  • Use yield from for the recursive case.
  • Only list instances recurse (strings are leaves).

Topics

Iterators & Generatorsyield from

Companies

MetaDropboxPalantir

Hints

Hint 1

if isinstance(item, list): yield from deep_flatten(item).

Hint 2

else: yield item.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.