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
Python - Ways to flatten a 2D list
Flattening a 2D list means converting a nested list structure into a single-dimensional list. Python provides several methods to accomplish this task, each with different performance characteristics and use cases.
Using itertools.chain.from_iterable()
The chain.from_iterable() function efficiently flattens a 2D list by chaining all sublists together ?
from itertools import chain
nested_list = [[1, 2, 3],
[3, 6, 7],
[7, 5, 4]]
print("Initial list:", nested_list)
# Converting 2D list into 1D using chain.from_iterable
flattened = list(chain.from_iterable(nested_list))
print("Flattened list:", flattened)
Initial list: [[1, 2, 3], [3, 6, 7], [7, 5, 4]] Flattened list: [1, 2, 3, 3, 6, 7, 7, 5, 4]
Using List Comprehension
List comprehension provides a concise and readable way to flatten lists ?
nested_list = [[1, 2, 3],
[3, 6, 7],
[7, 5, 4]]
print("Initial list:", nested_list)
# Converting 2D list into 1D using list comprehension
flattened = [item for sublist in nested_list for item in sublist]
print("Flattened list:", flattened)
Initial list: [[1, 2, 3], [3, 6, 7], [7, 5, 4]] Flattened list: [1, 2, 3, 3, 6, 7, 7, 5, 4]
Using functools.reduce()
The reduce() function applies a function cumulatively to combine all sublists ?
from functools import reduce
nested_list = [[1, 2, 3],
[3, 6, 7],
[7, 5, 4]]
print("Initial list:", nested_list)
# Converting 2D list into 1D using functools.reduce
flattened = reduce(lambda x, y: x + y, nested_list)
print("Flattened list:", flattened)
Initial list: [[1, 2, 3], [3, 6, 7], [7, 5, 4]] Flattened list: [1, 2, 3, 3, 6, 7, 7, 5, 4]
Using sum() Function
The sum() function can concatenate lists when given an empty list as the start value ?
nested_list = [[1, 2, 3],
[3, 6, 7],
[7, 5, 4]]
print("Initial list:", nested_list)
# Converting 2D list into 1D using sum()
flattened = sum(nested_list, [])
print("Flattened list:", flattened)
Initial list: [[1, 2, 3], [3, 6, 7], [7, 5, 4]] Flattened list: [1, 2, 3, 3, 6, 7, 7, 5, 4]
Comparison of Methods
| Method | Performance | Readability | Best For |
|---|---|---|---|
chain.from_iterable() |
Fastest | Good | Large lists |
| List comprehension | Fast | Excellent | Most cases |
reduce() |
Moderate | Fair | Functional programming |
sum() |
Slowest | Good | Small lists only |
Conclusion
For most cases, use list comprehension for its excellent readability. For performance-critical applications with large datasets, itertools.chain.from_iterable() is the fastest option. Avoid sum() for large lists due to performance overhead.
