Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Merging nested lists in Python
Nested lists are lists that contain other lists as elements. Sometimes we need to flatten these nested structures into a single list containing all elements. Python provides several approaches to merge nested lists, each suited for different scenarios.
Using Recursion for Deep Nesting
The recursive approach handles lists with multiple levels of nesting by checking each element and recursively processing nested lists ?
from collections.abc import Iterable
def flatten(lst):
for item in lst:
if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
yield from flatten(item)
else:
yield item
# Example with multiple nesting levels
nested_list = [[1, 2, 3], [4, [5, 6]], [7, 8, 9]]
result = list(flatten(nested_list))
print(result)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
This method works by checking if each item is iterable (but not a string or bytes). If it is, the function calls itself recursively. The yield from statement efficiently passes all values from the recursive call.
Using List Comprehension for Simple Nesting
For lists with only one level of nesting, list comprehension provides a concise solution ?
def flatten_simple(nested_list):
return [item for sublist in nested_list for item in sublist]
# Example with single-level nesting
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = flatten_simple(nested_list)
print(result)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Using itertools.chain for Performance
The itertools.chain method is memory-efficient and fast for single-level nesting ?
import itertools nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] result = list(itertools.chain.from_iterable(nested_list)) print(result)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Comparison
| Method | Nesting Level | Performance | Best For |
|---|---|---|---|
| Recursion | Multiple | Moderate | Deep nesting |
| List Comprehension | Single | Fast | Simple cases |
| itertools.chain | Single | Fastest | Large datasets |
Conclusion
Use recursion for deeply nested lists, list comprehension for simple single-level nesting, and itertools.chain for the best performance with single-level structures. Choose the method based on your nesting complexity and performance requirements.
