PythonMastery
Python programs · Lists · beginner

Flatten a nested list in Python

Turn a list of lists into one flat list in Python with a nested loop or a list comprehension, and flatten lists nested to any depth.

To flatten a list of lists means to take the items out of the inner lists and put them all in one list, in the same order.

The program

python
nested = [[1, 2], [3, 4, 5], [], [6]]

flat = []
for inner in nested:
    for item in inner:
        flat.append(item)

print(flat)
output
[1, 2, 3, 4, 5, 6]

How it works

The same two loops fit in one list comprehension. The for parts are in the same order as in the loop version:

python
nested = [[1, 2], [3, 4, 5], [], [6]]
flat = [item for inner in nested for item in inner]
print(flat)
output
[1, 2, 3, 4, 5, 6]

Lists nested to any depth

The versions above go only one level deep. When lists can hold lists that hold more lists, a recursive function handles every level: when an item is itself a list, the function calls itself on that item.

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

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

result.extend(...) adds every item of a list to result, while append would add the list as one item.

Learn the idea: Lists & Sequences, Loops: for, while, and the Pythonic Patterns, Comprehensions: Lists, Dicts, Sets, Generators

A longer explanation: How do I flatten a list of lists in Python?