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
| Call | Expected |
|---|---|
flatten([1, [2, [3, [4]]], 5]) | [1, 2, 3, 4, 5] |
flatten([]) | [] |
flatten([[], [[]]]) | [] |
flatten([['a', ['b']], 'c']) | ['a', 'b', 'c'] |
- A one-level comprehension handles
[[1], [2]]but not deeper nesting. - Call
flattenon each element that is itself a list, and check withisinstance(x, list).
Show solution
Python
def flatten(items):
out = []
for x in items:
if isinstance(x, list):
out.extend(flatten(x))
else:
out.append(x)
return outRecursion 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.
Why this works
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.