Flatten a Matrix Practice Problem
This data science coding problem helps you practice List & Dict Comprehensions, flatten a matrix, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of List & Dict Comprehensions.
- Problem ID: 92
- Problem key: 92-flatten-a-matrix
- URL: https://datacrack.app/solve/92-flatten-a-matrix
- Difficulty: medium
- Topic: List & Dict Comprehensions
- Module: Python Fundamentals
Problem Statement
# 🧩 Flatten a Matrix
---
### 🎯 Goal
Flattening a 2D matrix into a 1D list using a nested comprehension is a critical skill. In machine learning, images are stored as 2D pixel arrays but must often be flattened into 1D vectors before being passed to models. NumPy's `.flatten()` and `.ravel()` do exactly this at scale.
---
### 🔍 The Task
```
Input: [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
Row by row, left to right — every element ends up in one flat list.
---
### 💻 Task
Implement `flatten_matrix(matrix)` using a **nested list comprehension** (one line).
---
### 📥 Input
- `matrix`: a list of lists — all rows have the same length (rectangular matrix)
### 📤 Output
- A single flat list of all elements, row by row
---
### 🧩 Starter Code
```python
def flatten_matrix(matrix):
"""
Flatten a 2D matrix into a 1D list using a nested list comprehension.
Args:
matrix (list[list]): Rectangular 2D list
Returns:
list: All elements in row-major order
"""
# 🧠 TODO: Use a nested comprehension:
# for each row in matrix, for each element in row → collect element
pass
```
---
### 💡 Example
```python
flatten_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Expected: [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
---
### 🔑 Key Concepts
- Nested comprehension for flattening: `[elem for row in matrix for elem in row]`
- Note the order: outer loop is `for row`, inner loop is `for elem`
- This is the Python version of `np.array(matrix).flatten()`Starter Code
def flatten_matrix(matrix):
"""
Flatten a 2D matrix into a 1D list using a nested list comprehension.
Args:
matrix (list[list]): Rectangular 2D list
Returns:
list: All elements in row-major order
"""
# 🧠 TODO: Use a nested comprehension:
# for each row in matrix, for each element in row → collect element
pass