← Back to all snippets
PYTHON

Flatten a Nested List in Python with List Comprehension

Discover how to efficiently flatten a list containing other lists into a single, flat list using a concise Python list comprehension, perfect for processing nested data.

import itertools

# Example 1: Flattening a simple list of lists using list comprehension
nested_list1 = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flat_list_comprehension = [item for sublist in nested_list1 for item in sublist]
print(f"Flattened (list comprehension): {flat_list_comprehension}")

# Example 2: Flattening using sum() (for lists of non-string types, potentially less performant for large lists)
# The sum() trick concatenates lists. It needs an initial empty list.
nested_list2 = [[1, 2], [3], [4, 5, 6]]
flat_list_sum = sum(nested_list2, [])
print(f"Flattened (sum() trick): {flat_list_sum}")

# Example 3: Flattening using itertools.chain.from_iterable (most memory efficient for large iterables)
nested_list3 = [(10, 11), (12,), (13, 14, 15)] # Works with any iterables, including tuples
flat_list_itertools = list(itertools.chain.from_iterable(nested_list3))
print(f"Flattened (itertools.chain): {flat_list_itertools}")
How it works: This snippet illustrates three popular Python methods for flattening a list of lists (or other iterables) into a single list. The nested list comprehension `[item for sublist in nested_list for item in sublist]` offers a concise and readable way for simple one-level flattening. The `sum()` function, when used with an initial empty list `[]`, can concatenate lists. For larger datasets, `itertools.chain.from_iterable` is often the most memory-efficient and performant approach, as it processes elements lazily.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs