PYTHON

Flatten a List of Lists (Nested List) in Python

Learn various Python techniques to flatten a nested list (a list of lists) into a single, one-dimensional list using list comprehensions and `itertools.chain`.

import itertools

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

# Method 1: Using a nested list comprehension (simple and common)
flattened_comprehension = [item for sublist in nested_list for item in sublist]
# print(flattened_comprehension) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Method 2: Using sum() (works for lists of lists, generally less efficient for large lists)
flattened_sum = sum(nested_list, [])
# print(flattened_sum) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Method 3: Using itertools.chain (most memory efficient for large lists)
flattened_chain = list(itertools.chain.from_iterable(nested_list))
# print(flattened_chain) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
How it works: This snippet provides three different ways to flatten a list of lists into a single flat list. The nested list comprehension is often the most readable and Pythonic for straightforward cases. `sum()` can also be used but might be less efficient for very large lists due to repeated list creation. For maximum performance and memory efficiency with large, complex nested lists, `itertools.chain.from_iterable` is the recommended approach as it creates an iterator rather than an intermediate list.

Need help integrating this into your project?

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

Hire DigitalCodeLabs