SyntaxStudy
Sign Up
Python Flattening Nested Lists
Python Intermediate 3 min read

Flattening Nested Lists

Flattening Nested Lists

A nested comprehension can flatten a list of lists into a single list efficiently.

Example
nested = [[1,2], [3,4], [5,6]]
flat = [item for sublist in nested for item in sublist]
print(flat)
# [1, 2, 3, 4, 5, 6]
Pro Tip

For deeply nested structures, use itertools.chain.from_iterable instead.