Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

How to Flatten a List of Lists in Python

1 min read .
How to Flatten a List of Lists in Python

Python lists can contain other lists, which is useful for representing grouped or nested data. When you need a single sequence instead, you can flatten the nested structure in several ways.

1. Flatten One Level with a List Comprehension

For a list where every top-level item is another list:

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

This is concise and readable for one-level nesting.

2. Use itertools.chain

The standard library provides another efficient option:

from itertools import chain

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = list(chain.from_iterable(nested_list))
print(flat_list)

chain.from_iterable() is especially useful when you already work with iterables and want to avoid repeatedly concatenating lists.

3. Avoid sum(..., []) for Large Lists

You may see this pattern:

flat_list = sum(nested_list, [])

It works for lists of lists, but repeated list concatenation causes unnecessary copying and can become slow as the data grows. Prefer a comprehension or itertools.chain.

4. Flatten Arbitrarily Nested Lists Recursively

When nesting depth varies, a recursive function can walk each level:

def flatten(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            flat_list.extend(flatten(item))
        else:
            flat_list.append(item)
    return flat_list

nested_list = [[1, [2, 3]], [4, [5, 6]], [7, 8]]
print(flatten(nested_list))

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

This version deliberately treats only list objects as containers. That prevents strings, tuples, dictionaries, or other iterables from being flattened unexpectedly.

Conclusion

For one-level nesting, a list comprehension or itertools.chain.from_iterable() is usually the best choice. Use recursion only when the depth is genuinely variable, and avoid sum(..., []) for performance-sensitive code.

Related Posts

chevron-up