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
![[TIPS] Python: Flatten a List of Lists in One Line](/_next/image?url=https%3A%2F%2Fapi.cms.glinteco.com%2Fuploads%2Flarge_tips_python_flatten_a_list_of_lists_in_one_line_5ae089c5a9.png&w=3840&q=100)

![[One Package Per Day] Poetry: Deterministic Dependency Management](/_next/image?url=https%3A%2F%2Fapi.cms.glinteco.com%2Fuploads%2Flarge_one_package_per_day_poetry_deterministic_dependency_management_6c0e1efe35.jpg&w=3840&q=75)
