PythonMastery
Python programs · Useful programs · intermediate

Flatten a deeply nested list in Python

Turn a list with lists inside lists, at any depth, into one flat list. A recursive function, then a generator version with yield from.

A list of lists is easy to flatten with one loop. When lists can be nested at any depth, like [1, [2, [3, [4]]]], you need recursion: a function that calls itself for each inner list.

The program

python
def flatten(items):
    result = []
    for item in items:
        if isinstance(item, (list, tuple)):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result


print(flatten([1, [2, [3, [4, 5]]], 6]))
print(flatten([[], [1, (2, 3)], [[[]]], "abc"]))
print(flatten([]))
output
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 'abc']
[]

How it works

Python stops recursion at about 1,000 levels deep (RecursionError). Real data is almost never nested that deeply.

Another way: a generator

A generator gives back items one at a time with yield, instead of building a new list at every level. yield from passes on every item that the inner call yields:

python
def flatten(items):
    for item in items:
        if isinstance(item, (list, tuple)):
            yield from flatten(item)
        else:
            yield item


nested = [1, [2, [3, [4, 5]]], 6]
print(list(flatten(nested)))
print(sum(flatten(nested)))
output
[1, 2, 3, 4, 5, 6]
21

sum() can use the generator directly, without making a list first.

Learn the idea: Functions & Scoping, Lists & Sequences, Generators: Lazy Iteration with yield