Q&A library Python

How do I flatten a list of lists in Python?

Python Beginner comprehensionsflatteninglists

Short answer

Use a nested list comprehension for one level of nesting, which is both clear and fast. For arbitrary depth you need recursion, and for numeric grids reach for numpy instead.

The short version

For a list nested one level deep, a nested list comprehension is the clearest and fastest option. Read it as an outer loop over the sublists and an inner loop over each sublist's items. For unknown or deeper nesting you need a recursive approach, and for numeric data a numpy array's ravel is simplest.

The comprehension

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

flat = [item for sub in nested for item in sub]
print(flat)   # [1, 2, 3, 4, 5]

The order of the two for clauses matches how you would write nested loops: the outer loop first, the inner loop second.

Why not sum

You may see the trick sum(nested, []). It works, but it is quietly quadratic, building a new list at every step, so it becomes slow on large inputs. It reads cleverly rather than clearly. Prefer the comprehension, or itertools.chain.

The itertools way

For flattening many sublists efficiently, chain.from_iterable is idiomatic and reads well.

from itertools import chain

flat = list(chain.from_iterable(nested))

This streams through the sublists without building intermediate lists, so it is a good choice when performance matters.

Deeper or unknown nesting

The comprehension only removes one level. A list like [1, [2, [3, 4]]] needs recursion, because you cannot know the depth in advance.

def flatten(items):
    for x in items:
        if isinstance(x, list):
            yield from flatten(x)
        else:
            yield x

print(list(flatten([1, [2, [3, 4]]])))   # [1, 2, 3, 4]

Numeric grids

If your "list of lists" is really a rectangular grid of numbers, a numpy array is the right tool, and flattening is a single call.

import numpy as np
np.array([[1, 2], [3, 4]]).ravel()   # array([1, 2, 3, 4])

Match the tool to the shape of your data: comprehension for one level, recursion for ragged depth, numpy for numeric grids.

Enjoying these?

Go from piecing together answers to real fluency.

Our courses take you from looking things up to doing the work with confidence, step by step on real data.

Browse the courses