Skip to content

Recursion · routine

Flatten

Write flatten(items) for a list whose elements are numbers or more lists, nested any depth, returning one flat list of the numbers in order.

flatten([1, [2, [3, 4]], 5]) is [1, 2, 3, 4, 5]. isinstance(x, list) tells you whether x is a list.

Run adds print(flatten([1, [2, [3, 4]], 5])) after your code, to try it.

Stuck on the idea rather than the code? The Recursion lesson walks through it.