Split an Array into Chunks Practice Problem
This data science coding problem helps you practice Array Manipulation, split an array into chunks, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Array Manipulation.
- Problem ID: 61
- Problem key: 61-split-an-array-into-chunks
- URL: https://datacrack.app/solve/61-split-an-array-into-chunks
- Difficulty: easy
- Topic: Array Manipulation
- Module: NumPy Foundations
Problem Statement
# 🧩 Split an Array into Chunks
---
### 🎯 Goal
Splitting arrays into equal-sized chunks is the foundation of **mini-batch training** in machine learning. Instead of updating model weights after every single sample (stochastic) or the entire dataset (batch), mini-batch gradient descent splits data into fixed-size chunks and updates weights after each chunk — a balance of speed and stability.
---
### 🔍 The Task
Split a 1D array into `n_chunks` equal pieces:
```
[1, 2, 3, 4, 5, 6], n_chunks=2 → [[1,2,3], [4,5,6]]
[1,2,...,12], n_chunks=3 → [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
```
---
### 💻 Task
Implement `split_into_chunks(data, n_chunks)` using `np.array_split()`.
---
### 📥 Input
- `data`: list of numbers — length divisible by `n_chunks`
- `n_chunks`: int — number of chunks to split into
### 📤 Output
- A list of lists — each inner list is one chunk
---
### 🧩 Starter Code
```python
import numpy as np
def split_into_chunks(data, n_chunks):
"""
Split a 1D array into n_chunks equal pieces.
Args:
data (list): Input 1D array
n_chunks (int): Number of chunks to split into
Returns:
list[list]: List of n_chunks sub-arrays
"""
arr = np.array(data)
# 🧠 TODO
pass
```
---
### 🔑 Key Concepts
- In this problem, `len(data)` is divisible by `n_chunks`, so the chunks are equal-sized
- `np.array_split(arr, n)` splits an array into `n` chunks
- If the length is not divisible by `n`, `np.array_split()` still works and makes chunks as even as possible
- `np.split(arr, n)` requires equal division and raises an error if the length is not divisibleStarter Code
import numpy as np
def split_into_chunks(data, n_chunks):
"""
Split a 1D array into n_chunks equal pieces.
Args:
data (list): Input 1D array
n_chunks (int): Number of chunks to split into
Returns:
list[list]: List of n_chunks sub-arrays
"""
arr = np.array(data)
# 🧠 TODO
pass