Python Flatten List

Learn how to flatten a list of lists in Python using list comprehension, itertools.chain.from_iterable, nested loops, recursion for deep nesting, and NumPy, plus when to avoid sum() on large data.

Published

Updated

Read time 4 min read

Reviewed byDeepak Prasad

Python Flatten List

Flattening turns a nested structure (often a list of lists) into a single sequence. For a shallow list of lists, pick the style your team prefers; for irregular depth, use recursion or a stack-based walker.

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

flat = [x for row in nested for x in row]

print(flat)
Output

You should see [1, 2, 3, 4, 5, 6, 7, 8, 9]. The standard library documents itertools.chain.from_iterable as the usual helper for this “iterable of iterables” shape (itertools docs).

For list basics, see Python list. When flattening is part of merging many sublists, see concatenate lists in Python.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Best way to flatten a list in Python

For a single level of nesting, itertools.chain.from_iterable is clear and efficient: it walks each inner iterable without building intermediate full copies the way repeated concatenation can.

python
from itertools import chain

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

print(list(chain.from_iterable(nested)))
Output

You should see [1, 2, 3, 4, 5].

A list comprehension is equally idiomatic when the logic stays on one line. Choose based on readability inside your codebase.


Flatten a list of lists using list comprehension

Two for clauses walk the outer list, then each inner list. For more comprehension patterns, see list comprehension in Python.

python
nested = [[10, 20], [30]]

flat = [value for row in nested for value in row]

print(flat)
Output

You should see [10, 20, 30].


Flatten a list using itertools.chain.from_iterable()

chain.from_iterable returns an iterator; wrap it in list() when you need a list.

python
from itertools import chain

data = [["a", "b"], ["c"]]

print(list(chain.from_iterable(data)))
Output

You should see ['a', 'b', 'c'].


Flatten a list using a nested for loop

Explicit loops mirror the comprehension and are easy to debug.

python
nested = [[1, 2], [3]]
flat = []

for row in nested:
    for x in row:
        flat.append(x)

print(flat)
Output

You should see [1, 2, 3].


Flatten deeply nested lists using recursion

When inner elements can themselves be lists, recurse until you hit a non-list leaf. This version only treats list instances as containers; tuples or other iterables stay as single values unless you extend the logic.

python
def flatten(items):
    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

You should see [1, 2, 3, 4, 5].


Flatten a NumPy array

NumPy is not in the standard library; install it in your environment when you already depend on it for numeric work. concatenate then tolist() is a common path from ragged row lists to a flat Python list.

python
import numpy as np

nested = [[1, 2], [3, 4]]
print(np.concatenate(nested).tolist())

You should see [1, 2, 3, 4]. For very large arrays, stay in NumPy land as long as possible instead of copying back to Python lists repeatedly.


Why you should avoid sum() for large lists

sum(nested, []) starts from an empty list and repeatedly does result + next_row. Each + allocates a new list and copies all elements accumulated so far, so total work grows roughly with the square of the number of rows. It is fine for tiny demos; for long inputs, prefer chain.from_iterable, a comprehension, or an explicit accumulator that extends a single list in place.

python
small = [[1], [2], [3]]
print(sum(small, []))
Output

You should see [1, 2, 3] on toy data—just do not scale this pattern to massive nested tables.


One-level flatten vs deep flatten

  • One-level: every element of the outer list is itself an iterable of atoms, for example [[1, 2], [3]]. List comprehension, chain.from_iterable, and a double for loop only peel one layer.
  • Deep: elements may be lists nested arbitrarily, for example [1, [2, [3]]]. You need recursion, an explicit stack, or a library that understands your shape.

Mixing both in one dataset means you must decide whether non-list iterables (tuples, strings) should be treated as atoms or walked character by character—isinstance(x, list) avoids flattening strings into characters.


Python flatten list quick reference table

Situation Approach
One level, readable [x for row in nested for x in row]
One level, lazy iterator chain.from_iterable(nested)
One level, imperative Nested for with .append
Arbitrary list nesting Recursive flatten helper
Numeric 2D data NumPy concatenate / reshape / flatten
Tiny toy data only sum(nested, []) (avoid large inputs)

Summary

Flattening a list of lists means producing one linear sequence. Use a comprehension or itertools.chain.from_iterable for a single level of nesting, explicit loops when teaching or debugging, and a small recursive helper when depth varies. Avoid sum(..., []) on large inputs because of repeated copying, and reach for NumPy when you are already in an array workflow.


References


Frequently Asked Questions

1. What is the difference between one-level and deep flattening?

One-level flattening only opens the outer list once; deep flattening walks every nested list until it reaches non-list leaves, which needs recursion or an explicit stack.

2. Why is sum(list_of_lists, []) discouraged for huge inputs?

Each + builds a new list and copies everything seen so far, so the work grows quadratically with the number of rows; itertools.chain or a comprehension avoids repeated full copies.

3. Does flattening change the original nested list?

The techniques here build a new flat list; the nested structure is left in place unless your own code clears or mutates it.

4. When should I use itertools.chain.from_iterable?

Use it for a clean one-level flatten of an iterable of iterables; it is lazy until you consume it and reads well in team codebases.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …