Skip to content

Flatten a nested list

Flatten a nested list

A list can hold integers and other lists, nested to any depth: [1, [2, 3], [4, [5, 6]]]. Return one flat list of the integers in order: [1, 2, 3, 4, 5, 6].

Recursion fits perfectly. Loop over each item: if it's a list, flatten it and add the results; otherwise it's an integer, so add it directly. Use isinstance(item, list) to tell them apart.

Log in or create account

IGCSE & A-Level