[TIPS] Python: Flatten a List of Lists in One Line
By khoanc, at: July 16, 2025, 5:33 p.m.
Estimated Reading Time: __READING_TIME__ minutes
![[TIPS] Python: Flatten a List of Lists in One Line](/media/filer_public_thumbnails/filer_public/b6/9e/b69ec84d-bb8c-45fd-8cee-f0cdff402a5b/python-flatten-list.png__1500x900_q85_crop_subsampling-2_upscale.jpg)
![[TIPS] Python: Flatten a List of Lists in One Line](/media/filer_public_thumbnails/filer_public/b6/9e/b69ec84d-bb8c-45fd-8cee-f0cdff402a5b/python-flatten-list.png__400x240_q85_crop_subsampling-2_upscale.jpg)
When working with Python, you’ll often encounter this common situation:
You have a list of lists, and you want to flatten it into a single list.
The Problem
Here’s an example:
data = [[1, 2], [3, 4], [5, 6]]
Desired output:
[1, 2, 3, 4, 5, 6]
The Simple Solution: List Comprehension
The most Pythonic way to flatten a list of lists is:
flattened = [item for sublist in data for item in sublist]
Explanation
This is a nested list comprehension, which is functionally equivalent to:
flattened = []
for sublist in data:
for item in sublist:
flattened.append(item)
But in a much more concise form.
Alternative: Using itertools.chain
For larger or memory-sensitive datasets, you can use Python’s built-in itertools module:
import itertools
flattened = list(itertools.chain.from_iterable(data))
This approach creates an iterator, which can be more efficient when working with large amounts of data.
Example
data = [['a', 'b'], ['c', 'd'], ['e']]
flattened = [item for sublist in data for item in sublist]
print(flattened)
# Output: ['a', 'b', 'c', 'd', 'e']
Best Practice
-
Use list comprehension for clear and concise code when working with small to medium datasets.
-
Use itertools.chain when working with large data or when you want to process items lazily.
This technique is a staple in clean Python development and is widely used in data manipulation, web scraping, and data pipelines.
Reference: StackOverflow’s top answer