Python Program to Flatten a Nested List of Any Depth

Short answer
To flatten a list of lists one level, use [x for row in nested for x in row]. For unknown depth, use a recursive function.

"Flattening" turns a nested list such as [[1, 2], [3], [4, 5]] into one list, [1, 2, 3, 4, 5]. You need it when data arrives grouped, for example orders per customer or rows of a table, and you want to process every value together.

There are two different problems hiding under one name: flattening one level (easy, one line) and flattening any depth (needs recursion). Pick the right tool for yours. A shorter how-to is also available at flatten a list.

Quick facts
InputA list that contains other lists, e.g. [[1, 2], [3, 4]]
OutputA single list with all the inner items
ApproachLoop over inner lists and collect their items, or recurse for deeper nesting
Time complexityO(n) for n total items

Approach to flatten a list step by step

One level: 1. Create an empty result list. 2. For each inner list, add its items to the result (extend() or an inner loop).

Any depth: 1. Go through each element of the input. 2. If the element is a list, flatten it first by calling the same function (recursion). 3. Otherwise add the element to the result.

The base case is the element that is not a list: it is added directly, which stops the recursion.

How the flatten code works

The comprehension [x for row in nested for x in row] reads like the equivalent nested loops written in the same order: first for row in nested, then for x in row. It creates the result in one expression.

The recursive version checks isinstance(item, list). Testing for list rather than "is iterable" matters: strings are iterable, and treating them as containers would split "ab" into letters, forever, since each letter is again a string.

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

Other ways to flatten nested lists

itertools.chain.from_iterable(nested) flattens one level lazily and is efficient; wrap it in list() to materialise it (see itertools). sum(nested, []) also works but copies the growing list every time, so it is slow for large inputs. Prefer the comprehension or chain. For numeric tables, NumPy offers array.flatten().

MethodDepthNotes
List comprehensionOne levelClear and fast
itertools.chain.from_iterableOne levelLazy, memory friendly
Loop with extend()One levelEasiest to read for beginners
Recursive functionAny depthNeeded for irregular nesting
sum(nested, [])One levelQuadratic time; avoid for big data

Examples you can run

Press Run, then edit the code and run it again.

Flatten one level with a comprehension

Each inner list is unpacked in order.

Flatten one level with a comprehension
nested = [[1, 2], [3], [4, 5, 6]]
flat = [x for row in nested for x in row]
print(flat)
Expected output[1, 2, 3, 4, 5, 6]

Flatten with chain and with extend()

Two other one-level approaches.

Flatten with chain and with extend()
from itertools import chain

nested = [["a", "b"], ["c"], []]
print(list(chain.from_iterable(nested)))

flat = []
for row in nested:
    flat.extend(row)
print(flat)
Expected output['a', 'b', 'c']
['a', 'b', 'c']

Flatten any depth with recursion

Lists inside lists inside lists are all unpacked.

Flatten any depth with recursion
def flatten(items):
    flat = []
    for item in items:
        if isinstance(item, list):
            flat.extend(flatten(item))
        else:
            flat.append(item)
    return flat

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

Interactive: build and flatten rows

Read two lines of numbers and merge them into one list.

Interactive: build and flatten rows
rows = []
for _ in range(2):
    line = input("Row: ")
    rows.append([int(x) for x in line.split()])
print(rows)
print([x for row in rows for x in row])
Expected outputRow: 1 2 3
Row: 4 5
[[1, 2, 3], [4, 5]]
[1, 2, 3, 4, 5]

Common mistakes

Copying the outer list instead of flattening

✗ Wrong

nested = [[1, 2], [3]]
flat = []
for row in nested:
    flat.append(row)
print(flat)
[[1, 2], [3]] (still nested, because append adds each inner list as one item)

✓ Right

nested = [[1, 2], [3]]
flat = []
for row in nested:
    flat.extend(row)
print(flat)

Use extend(row) or an inner loop to add the inner items.

Using the one-level comprehension on mixed data

✗ Wrong

data = [1, [2, 3]]
print([x for row in data for x in row])
TypeError: 'int' object is not iterable

✓ Right

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

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

Every element must be a list for the one-level version. Use the recursive function when some elements are plain values.

Python Program to Flatten a Nested List of Any Depth: questions people ask

How do I flatten a list of lists in Python?

Use [x for row in nested for x in row], or list(itertools.chain.from_iterable(nested)). Both flatten exactly one level.

How do I flatten a list with unknown nesting depth?

Write a recursive function that calls itself for each item that is a list and appends everything else. Python has no built-in function for it.

Is sum(nested, []) a good way to flatten?

It works but is slow, because each + creates a new list, so the time grows quadratically. Prefer a comprehension or chain.

Keep learning

Step-by-step lessons:
Python ListsPython RecursionPython List Comprehensions

Related:
How to Flatten a List of Lists in PythonPython Program to Transpose a MatrixPython List extend() MethodPython itertools

More in list and dictionary programs:
Python Program to Find the Largest Number in a ListPython Program to Find the Second Largest Number in a ListPython Program to Calculate the Average of a ListPython Program to Transpose a MatrixPython Program to Merge Two Sorted Lists See all →