IntermediateRecursion

Flatten a nested list

Task

Write flatten(items) that turns a list nested to any depth into a flat list, keeping the order. Strings are values, not lists: do not split them into characters.

Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.

Tests
CallExpected
flatten([1, [2, [3, [4]]], 5])[1, 2, 3, 4, 5]
flatten([])[]
flatten([[], [[]]])[]
flatten([['a', ['b']], 'c'])['a', 'b', 'c']
Show solution
Python
def flatten(items):
    out = []
    for x in items:
        if isinstance(x, list):
            out.extend(flatten(x))
        else:
            out.append(x)
    return out

Recursion matches the shape of the data. Checking for "iterable" instead of list is a classic bug: strings are iterable, and a one-character string contains itself, so the recursion never ends.

Revise in the Python guide, or test yourself with the Python practice sets.