How to Flatten a List of Lists in Python
Learn how to flatten a list of lists in Python. Compare nested list comprehensions, itertools.chain, sum, and recursive methods with code examples.
Explanation
When working with matrix calculations, database rows, or parsed data trees, you will frequently encounter nested structures, such as a list of lists: `[[1, 2], [3, 4]]`. Flattening this structure means converting it into a single-dimensional list containing all individual elements: `[1, 2, 3, 4]`. Python offers several elegant ways to achieve this.
The most common and pythonic way to flatten a list of lists is using a nested list comprehension: `[item for sublist in matrix for item in sublist]`. While the syntax can look slightly counter-intuitive at first because the loops are written in the same order as a nested `for` loop, it is highly optimized, fast, and does not require importing external libraries.
Alternatively, you can use the `itertools` module's `chain.from_iterable()` function. This is the most memory-efficient approach because it returns an iterator that yields elements lazily rather than allocating a new list in memory immediately. For deeply nested lists (with arbitrary depth), you must write a recursive generator function to unpack all levels.
Step-by-Step Implementation
- 1
Use a nested list comprehension [item for sublist in nested_list for item in sublist] for flat 2D structures.
- 2
Import itertools and call itertools.chain.from_iterable(nested_list) for lazy, memory-friendly evaluation.
- 3
Define a recursive function checking isinstance(item, list) to handle arbitrarily nested collections.
Code Example
This script demonstrates flattening a list of lists using list comprehensions, itertools.chain, and recursive unpacking.
import itertools
matrix = [[1, 2, 3], [4, 5], [6, 7, 8]]
# Method 1: List comprehension (Pythonic and fast)
flat_comp = [item for sublist in matrix for item in sublist]
print("List comprehension:", flat_comp)
# Method 2: itertools.chain (Highly memory efficient)
flat_chain = list(itertools.chain.from_iterable(matrix))
print("itertools.chain:", flat_chain)
# Method 3: Recursive function for deep/irregular nesting
irregular = [1, [2, 3], [[4, 5], 6]]
def flatten_deep(items):
result = []
for item in items:
if isinstance(item, list):
result.extend(flatten_deep(item))
else:
result.append(item)
return result
print("Deep flatten:", flatten_deep(irregular))List comprehension: [1, 2, 3, 4, 5, 6, 7, 8]
itertools.chain: [1, 2, 3, 4, 5, 6, 7, 8]
Deep flatten: [1, 2, 3, 4, 5, 6]Frequently Asked Questions
Can I use the sum() function to flatten lists?
Yes, sum(matrix, []) will work, but it is highly discouraged. It runs in O(N^2) complexity because it creates a new list copy on every addition, causing terrible performance for large datasets.
What is the fastest method to flatten lists of lists?
itertools.chain.from_iterable() is usually the fastest, followed closely by nested list comprehensions.
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Variables & Data Types Explained
Understand Python variables and core data types (strings, integers, floats, booleans). A complete beginner guide to memory assignment in Python.
Python List Methods
Quick reference guide for Python list operations. Master appending, inserting, removing, sorting, and slicing elements.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.