How to Flatten a Matrix in Python: Simple Methods Explained
To flatten a matrix in Python, you can use a list comprehension like
[item for row in matrix for item in row] or use itertools.chain.from_iterable(matrix) for an iterator. These methods convert a list of lists (matrix) into a single flat list.Syntax
Here are two common ways to flatten a matrix (a list of lists) in Python:
[item for row in matrix for item in row]: This is a list comprehension that goes through each row, then each item in that row, collecting all items into one list.list(itertools.chain.from_iterable(matrix)): This uses thechainfunction from theitertoolsmodule to flatten the matrix efficiently.
python
import itertools flat_list = [item for row in matrix for item in row] flat_list_chain = list(itertools.chain.from_iterable(matrix))
Example
This example shows how to flatten a 2D matrix (list of lists) into a single list using both methods.
python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Using list comprehension flat_list = [item for row in matrix for item in row] print(flat_list) # Using itertools.chain import itertools flat_list_chain = list(itertools.chain.from_iterable(matrix)) print(flat_list_chain)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Common Pitfalls
One common mistake is trying to flatten the matrix with a single for loop, which only iterates over rows, not individual elements. Another is using sum(matrix, []), which works but is inefficient for large matrices.
Correct way with list comprehension:
flat_list = [item for row in matrix for item in row]
Incorrect way (only flattens one level incorrectly):
flat_list = [item for item in matrix]
Less efficient but works:
flat_list = sum(matrix, [])
python
matrix = [[1, 2], [3, 4]] # Incorrect flattening (only copies rows) flat_wrong = [item for item in matrix] print(flat_wrong) # Output: [[1, 2], [3, 4]] # Correct flattening flat_correct = [item for row in matrix for item in row] print(flat_correct) # Output: [1, 2, 3, 4]
Output
[[1, 2], [3, 4]]
[1, 2, 3, 4]
Quick Reference
Summary of methods to flatten a matrix:
| Method | Description | Example |
|---|---|---|
| List comprehension | Flatten by looping through rows and items | [item for row in matrix for item in row] |
| itertools.chain | Efficient iterator flattening | list(itertools.chain.from_iterable(matrix)) |
| sum (less efficient) | Concatenate lists using sum | sum(matrix, []) |
Key Takeaways
Use list comprehension [item for row in matrix for item in row] to flatten a matrix simply and clearly.
itertools.chain.from_iterable(matrix) is an efficient alternative for flattening.
Avoid using a single for loop that iterates only over rows, as it won't flatten the matrix.
Using sum(matrix, []) works but is slower and not recommended for large data.
Flattening converts a list of lists into a single list containing all elements in order.