Flatten an Arbitrarily Nested List

Medium ⏱ 12 min 57% acceptance ★★★★☆ 4.2
Implement flatten(nested) that returns a single flat list of values from a list that may contain other lists nested to any depth, using recursion.

Examples

Example 1
Input
flatten([1, [2, [3, 4], 5], 6])
Output
[1, 2, 3, 4, 5, 6]
Explanation

Every nested list is recursively expanded in order.

Example 2
Input
flatten([[1], [2, [3]], []])
Output
[1, 2, 3]
Explanation

Empty sublists contribute nothing.

Constraints

  • nested contains ints and/or lists (nested to any depth).

Topics

RecursionLists

Companies

AmazonWalmart

Hints

Hint 1

For each item, check isinstance(item, list).

Hint 2

If it is a list, extend the result with flatten(item); 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.