Home / Python / Example programs / Lists

Python program: Flatten a nested list

Turn a list of lists into one flat list.

The code

nested = [[1, 2], [3], [4, 5, 6]]
print([x for row in nested for x in row])

def flatten(items):
    """Any depth, with recursion."""
    out = []
    for x in items:
        if isinstance(x, list):
            out.extend(flatten(x))
        else:
            out.append(x)
    return out

print(flatten([1, [2, [3, [4]], 5]]))

Output

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]

How it works

A comprehension with two for parts handles one level. For any depth, the function calls itself on inner lists.

Python features used

Learn the ideas behind it in the free lesson More Functions.