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