Neural Mastery
← Practice
Chunk a List into Batcheseasy

Chunk a List into Batches

easy Python for AI 10–15 min

NumPy allowed · plain Python earns 10 bonus points

RAG step 1/4

A query retrieves context

Embedding similarity ranks the documents before generation.
Open lesson →
01query
02embed
03retrieve
04context
What is RAG?→ embed →top context
retrieval.md44%
rag-systems.md33%
agents.md24%

Cosine-like similarity scores ranked before context assembly

Partition a flat list into fixed-size batches -- the standard pattern used in LLM prompt batching, database bulk insertion, and mini-batch gradient descent.

Related Skills

Task

Implement chunk_list(items, chunk_size): partition items into sublists of length chunk_size. The final chunk contains the remaining elements if len(items) is not evenly divisible. Raise ValueError if chunk_size <= 0. If items is empty, return [].

Function Signature

chunk_list(items: list, chunk_size: int) -> list[list]

Examples

Example 1: Uneven List Length
Input: items = [1, 2, 3, 4, 5, 6, 7] chunk_size = 3
Output: [[1, 2, 3], [4, 5, 6], [7]]
Example 2: Exact Multiple Length
Input: items = [10, 20, 30, 40] chunk_size = 2
Output: [[10, 20], [30, 40]]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Must raise ValueError if chunk_size is less than or equal to 0.
  • The last chunk may contain fewer elements than chunk_size.
  • Empty input list returns [].
Python3Saved ✓
def chunk_list(items: list, chunk_size: int) -> list[list]:
"""Split a list into consecutive chunks of at most chunk_size length.

The final chunk may be smaller if len(items) is not divisible by
chunk_size. Raises ValueError if chunk_size <= 0. Empty list returns []."""
# Your implementation here
pass

Case 1: Uneven List Length
Input: items = [1, 2, 3, 4, 5, 6, 7] chunk_size = 3
Expected: [[1, 2, 3], [4, 5, 6], [7]]
Case 2: Exact Multiple Length
Input: items = [10, 20, 30, 40] chunk_size = 2
Expected: [[10, 20], [30, 40]]