How to Flatten a List of Lists in Python
[x for row in nested for x in row] or list(itertools.chain.from_iterable(nested)). For lists nested to unknown depth, use a small recursive function.A nested list, or list of lists, appears when you group data by row, read a CSV file, or collect results from several loops. Flattening means turning [[1, 2], [3], [4, 5]] into [1, 2, 3, 4, 5].
First decide how deep your nesting goes. One level (every inner item is a list, nothing deeper) has short, fast solutions. Irregular nesting such as [1, [2, [3, [4]]]] needs recursion. Background on nested structures is in nested data.
| One level, readable | [x for row in nested for x in row] |
|---|---|
| One level, fast | list(itertools.chain.from_iterable(nested)) |
| Any depth | A recursive function |
| Avoid | sum(nested, []) (slow for big lists) |
| Returns | A new flat list; the nested list is unchanged |
Flatten one level with a nested list comprehension
Read the comprehension from left to right as two loops: for each row in nested, for each x in row, collect x. It is the same as writing two nested for loops, just shorter. See list comprehensions for the syntax.
nested = [[1, 2], [3], [4, 5]]
flat = [x for row in nested for x in row]
print(flat)Flatten with itertools.chain.from_iterable()
chain.from_iterable() from the itertools module walks through each inner list in turn and yields their items one after another. It is fast and does not build any intermediate lists.
from itertools import chain
nested = [[1, 2], [3], [4, 5]]
print(list(chain.from_iterable(nested)))Flatten a list with unknown or mixed nesting depth
When some items are lists and others are plain values, check each item with isinstance(item, list). If it is a list, flatten it recursively; otherwise keep it. This is a good use of recursion. Strings are not lists, so they stay whole.
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])) # [1, 2, 3, 4, 5]
Why sum(nested, []) is a poor choice
sum(nested, []) works because + joins lists, but it builds a new list at every step, so it gets quadratically slower as the data grows. It is fine for a quick demo, not for real data.
Flattening methods compared
| Method | Handles depth | Speed | Readability |
|---|---|---|---|
| Nested comprehension | One level | Fast | Good |
chain.from_iterable | One level | Fastest | Very good |
| Recursive function | Any depth | Slower | Good |
sum(nested, []) | One level | Slow (O(n squared)) | Short but misleading |
Examples you can run
Press Run, then edit the code and run it again.
Flatten one level with a comprehension
Each row is a list of marks for one student.
marks = [[70, 80], [90], [60, 75, 85]]
flat = [m for row in marks for m in row]
print(flat)
print(sum(flat) / len(flat))Expected output[70, 80, 90, 60, 75, 85]
76.66666666666667
Flatten with itertools.chain
The same result with the standard library.
from itertools import chain
basket = [["pen", "ink"], ["book"], []]
print(list(chain.from_iterable(basket)))Expected output['pen', 'ink', 'book']
Flatten any depth with recursion
Mixed items and deeper nesting are handled by calling the function on inner lists.
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]))
print(flatten([]))Expected output[1, 2, 3, 4, 5]
[]
Strings are not split into characters
Because the check is isinstance(item, list), a string stays one item.
def flatten(items):
out = []
for item in items:
if isinstance(item, list):
out.extend(flatten(item))
else:
out.append(item)
return out
print(flatten(["ab", ["cd", ["e"]]]))Expected output['ab', 'cd', 'e']
Common mistakes
Getting the loop order wrong in the comprehension
✗ Wrong
nested = [[1, 2], [3]]
flat = [x for x in row for row in nested]✓ Right
nested = [[1, 2], [3]]
flat = [x for row in nested for x in row]The outer loop comes first: for row in nested, then for x in row.
Using a one-level method on deeper data
✗ Wrong
nested = [[1, [2]], [3]]
print([x for row in nested for x in row])✓ Right
def flatten(items):
out = []
for i in items:
if isinstance(i, list):
out.extend(flatten(i))
else:
out.append(i)
return out
print(flatten([[1, [2]], [3]]))Comprehensions and chain flatten exactly one level. Use a recursive function for deeper nesting.
Flattening a list that contains plain values
✗ Wrong
mixed = [[1, 2], 3]
print([x for row in mixed for x in row])✓ Right
mixed = [[1, 2], 3]
print([x for row in mixed for x in (row if isinstance(row, list) else [row])])A one-level flatten expects every item to be a list. Check types, or use the recursive version.
How to Flatten a List of Lists in Python: questions people ask
How do I flatten a list of lists in Python?
Use a nested list comprehension, [x for row in nested for x in row], or list(itertools.chain.from_iterable(nested)). Both return a new one-level list.
How do I flatten a deeply nested list in Python?
Write a recursive function that extends the result with the flattened version of every inner list and appends everything else. Comprehensions only go one level deep.
Is there a built-in flatten function in Python?
No. Python has no flatten() built-in, which is why people use itertools.chain.from_iterable() or a comprehension.
Keep learning
Step-by-step lessons:
Python List ComprehensionsPython Nested Data StructuresPython itertools
Related:
Python Program to Flatten a Nested List of Any DepthPython List extend() MethodPython Program to Transpose a MatrixHow to Remove Duplicates from a List in Python
More in lists, dicts and sets:
How to Remove Duplicates from a List in PythonHow to Sort a Dictionary by Value in PythonHow to Merge Two Dictionaries in PythonHow to Reverse a List in PythonHow to Check if a List Is Empty in PythonHow to Get the Last Element of a List in PythonHow to Loop Through a Dictionary in PythonHow to Count Occurrences in a List in Python See all →