Start free

Advanced · Recursion · 164 of 264

Flatten a nested list

A list can contain numbers and other lists, nested to any depth. Print all the numbers in order. Read it with ast.literal_eval(input()).

Input: a nested list such as [1, [2, [3, 4]], 5] Output: the numbers on one line, separated by spaces.

Examples

Input
[1, [2, [3, 4]], 5]
Output
1 2 3 4 5
Input
[[[[7]]]]
Output
7
Input
[1, 2, 3]
Output
1 2 3

One more test checks other inputs when you press Check.

Stuck? The idea behind recursion

A recursive function calls itself on a smaller version of the problem, until it reaches a case small enough to answer directly (the base case).

Trust the smaller call to be right, and only work out how to build this answer from it.

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5))

Watch for: Without a base case, or if the problem doesn't get smaller, it never stops: Python gives up with a RecursionError.

All the recursion exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More recursion exercises