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) # [1, 2, 3, 4, 5, 6]
The two for clauses run left to right, just like nested loops: the first picks each inner list, the second picks each value.
Flatten with itertools.chain
from itertools import chain
nested = [[1, 2], [3, 4], [5, 6]]
flat = list(chain.from_iterable(nested))
print(flat) # [1, 2, 3, 4, 5, 6]
chain.from_iterable is fast and memory-friendly because it streams the items rather than building intermediate lists.
Flatten deeply nested lists recursively
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]]]])) # [1, 2, 3, 4]
The function calls itself whenever it finds a nested list, so it works no matter how many levels deep the data goes.
Which method should you use?
- Comprehension — the default for a single level of nesting.
- itertools.chain — when speed and large data matter.
- Recursion — when nesting depth is unknown or uneven.
- Common mistake: using a one-level method on data that is nested more deeply than expected.
Frequently asked questions
How do I flatten only one level but not deeper?
Use the comprehension or chain.from_iterable; both unwrap exactly one level and leave anything deeper intact.
Can I flatten a list of strings safely?
Be careful — strings are iterable, so a naive flatten can split them into characters. Check with isinstance(item, list) as the recursive version does.
Want to master loops and comprehensions? Start with our free Python course.