Python Program to Flatten a Nested List of Any Depth
[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.
| Input | A list that contains other lists, e.g. [[1, 2], [3, 4]] |
|---|---|
| Output | A single list with all the inner items |
| Approach | Loop over inner lists and collect their items, or recurse for deeper nesting |
| Time complexity | O(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.
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().
| Method | Depth | Notes |
|---|---|---|
| List comprehension | One level | Clear and fast |
itertools.chain.from_iterable | One level | Lazy, memory friendly |
Loop with extend() | One level | Easiest to read for beginners |
| Recursive function | Any depth | Needed for irregular nesting |
sum(nested, []) | One level | Quadratic 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.
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.
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.
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.
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)✓ 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])✓ 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 →