To flatten a list of lists into a single flat list in Python, you can use several methods depending on the structure of your data (e.g., single-level vs. deeply nested lists). Here are the most common and efficient approaches:
1. Single-Level Nesting
If your list contains lists at one level deep, use these methods:
List Comprehension (Pythonic and Readable)
list_of_lists = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in list_of_lists for item in sublist]
print(flat_list) # Output: [1, 2, 3, 4, 5, 6]
itertools.chain
(Efficient for Large Lists)
import itertools
list_of_lists = [[1, 2], [3, 4], [5, 6]]
flat_list = list(itertools.chain.from_iterable(list_of_lists))
print(flat_list) # Output: [1, 2, 3, 4, 5, 6]
sum
Function (Simple but Inefficient for Large Data)
list_of_lists = [[1, 2], [3, 4], [5, 6]]
flat_list = sum(list_of_lists, [])
print(flat_list) # Output: [1, 2, 3, 4, 5, 6]
2. Deeply Nested Lists
If your list has multiple levels of nesting, use a recursive approach:
def flatten(lst):
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten(item)) # Recurse for nested lists
else:
result.append(item)
return result
nested_list = [[1, [2, [3]]], [4, [5, 6]]]
flat_list = flatten(nested_list)
print(flat_list) # Output: [1, 2, 3, 4, 5, 6]
3. Alternative Methods
functools.reduce
(Functional Style)
from functools import reduce
import operator
list_of_lists = [[1, 2], [3, 4], [5, 6]]
flat_list = reduce(operator.concat, list_of_lists)
print(flat_list) # Output: [1, 2, 3, 4, 5, 6]
Generators (Memory-Efficient for Large Data)
def flatten_generator(lst):
for item in lst:
if isinstance(item, list):
yield from flatten_generator(item) # Yield recursively
else:
yield item
nested_list = [[1, [2, 3]], [4, [5, 6]]]
flat_list = list(flatten_generator(nested_list))
print(flat_list) # Output: [1, 2, 3, 4, 5, 6]
Key Differences
Method | Use Case | Pros & Cons |
---|---|---|
List Comprehension | Single-level nesting | Pythonic, readable, fast |
itertools.chain | Large datasets or performance-critical | Efficient, requires module import |
Recursive Flatten | Deeply nested lists | Handles arbitrary depth, risk of stack overflow for very deep nesting |
Generators | Memory efficiency for large data | Lazy evaluation, slower for small lists |
sum Function | Small lists | Simple syntax, but slow for large data (O(n²) ) |
Recommendations
- Single-level lists: Use list comprehension or
itertools.chain
. - Deeply nested lists: Use recursive flattening or generators.
- Avoid
sum
: Poor performance for large datasets.
By choosing the right method, you can efficiently flatten lists in Python!