← Back to challenges

Flatten the Nested List

PythonHardlanguage_fundamentalsarraysstrings

Instructions

In this challenge you will be given a nested list, such as the following:

[1, [2, 3], [4, [5, 6]], [7, [8, [9, 0]]]]

Just look at all those brackets... so confusing!

The goal is simple: write a function that turns a nested list as above into its flattened version, which in this example is:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Examples

flatten([[6, 7], [4, 5]]) ➞ [6, 7, 4, 5]

flatten([[[[[["cat"]]]]]]) ➞ ["cat"]

flatten([[3, [5, 6]], [9, 3]]) ➞ [3, 5, 6, 9, 3]

flatten([1, [2, 3], [4, [5, 6]], [7, [8, [9, 0]]]]) ➞ [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Notes

This one can be tricky, but with the right approach it's actually not hard at all. See the comments if you'd like a hint.

python3
Loading editor…
to run
Walks through the solution with reasoning and edge cases.