Flatten a Deeply Nested List

Hard ⏱ 18 min 39% acceptance ★★★★★ 4.9
Write deep_flatten(nested) that flattens a list which may contain other lists nested to any depth (not just one level) into a single flat list, preserving left-to-right order. Non-list elements should be kept as-is.

Examples

Example 1
Input
nested = [1, [2, [3, 4], 5], [[6]], 7]
Output
[1, 2, 3, 4, 5, 6, 7]
Explanation

Every level of nesting is unwrapped recursively.

Constraints

  • Nesting depth is reasonable (no stack-overflow-inducing depth).

Topics

ListsRecursionNested Lists

Companies

MetaAdobe

Hints

Hint 1

Recursion is natural here: if an element is itself a list, recurse into it; otherwise append it directly.

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