Skip to content
mlmentorship

Mini-Batches

Split examples into batches without dropping the final short batch.

Published · 10 min read ·Role-specific ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Mini-Batches

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A finite Python list items and a positive integer batch_size. Output. Yield consecutive list batches, each with at most batch_size items, until every input occurrence has been yielded. Rules. Preserve order. The final batch may be shorter and must not be discarded or padded. Do not mutate the input. List slices copy references, not the referenced objects. Empty input yields no batches. Nonpositive batch sizes are outside the contract. Example. Items [0, 1, 2, 3, 4] with batch size 2 yield [0, 1], then [2, 3], then [4]. With batch size 8, yield one batch containing all five items.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Advance one start cursor by batch size and yield the half-open slice; sequence slicing automatically clips the final end.

Problem trace

The final batch keeps the leftover example instead of dropping it

Worked example: bounded half-open slicing preserves a short tailSeven items and batch size 3 yield lengths 3,3,1. The last slice keeps item 6 rather than dropping or duplicating it.Seven distinct positions divide intothree, three, and oneEvery input identity appearsexactly once0123345361Slice [0:3] keeps 0, 1, 2Slice [3:6] keeps 3, 4, 5Slice [6:9] keeps 6The final request ends at nine, butonly real position six remains.
Read it this way: Seven items and batch size 3 yield lengths 3,3,1. The last slice keeps item 6 rather than dropping or duplicating it. Which real input identity disappears if the one-item final slice is discarded?
Full interview answer 10 min read
Reading depth

Divide an ordered collection into consecutive batches without dropping, duplicating, or reordering any item.

Problem

Input. A finite Python list items and a positive integer batch_size.

Output. Yield consecutive list batches, each with at most batch_size items, until every input occurrence has been yielded.

Rules. Preserve order. The final batch may be shorter and must not be discarded or padded. Do not mutate the input. List slices copy references, not the referenced objects. Empty input yields no batches. Nonpositive batch sizes are outside the contract.

Example. Items [0, 1, 2, 3, 4] with batch size 2 yield [0, 1], then [2, 3], then [4]. With batch size 8, yield one batch containing all five items.

Picture

Seven examples with size three use starts 0,3,6 and clipped stops 3,6,7. Every position belongs to exactly one half-open slice.

Problem trace

The final batch keeps the leftover example instead of dropping it

Input and goalSplit examples into batches without dropping the final short batch.
Validate the batch sizeSeven examples use batch_size=3. The positive-size guard passes.
start=00011last included=22233445566
batchSize3halfOpenSlice[0:3]guard3 > 0nextStart0
start
0
last included
2
batch size
3

Recognize it
Use it when every item must appear once in consecutive batches and the final batch may be shorter than the requested size.
Keep true
Before each yield, indexes below start have appeared exactly once; items[start:start+batch_size] contributes the next non-overlapping range, clipped only by sequence length.
Reuse it
Use half-open slices and a fixed stride to partition ordered data without overlap; let bounded slicing handle a short tail explicitly.
Seven examples use batch_size=3. The positive-size guard passes. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does items[6:9] contain one item rather than three, and is any example dropped?
Reference drawing

Problem trace

The final batch keeps the leftover example instead of dropping it

Worked example: bounded half-open slicing preserves a short tailSeven items and batch size 3 yield lengths 3,3,1. The last slice keeps item 6 rather than dropping or duplicating it.Seven distinct positions divide intothree, three, and oneEvery input identity appearsexactly once0123345361Slice [0:3] keeps 0, 1, 2Slice [3:6] keeps 3, 4, 5Slice [6:9] keeps 6The final request ends at nine, butonly real position six remains.
Execution trace
Input and goalSplit examples into batches without dropping the final short batch.
Validate the batch sizeSeven examples use batch_size=3. The positive-size guard passes.
start=00011last included=22233445566
batchSize3halfOpenSlice[0:3]guard3 > 0nextStart0
start
0
last included
2
batch size
3

Recognize it
Use it when every item must appear once in consecutive batches and the final batch may be shorter than the requested size.
Keep true
Before each yield, indexes below start have appeared exactly once; items[start:start+batch_size] contributes the next non-overlapping range, clipped only by sequence length.
Reuse it
Use half-open slices and a fixed stride to partition ordered data without overlap; let bounded slicing handle a short tail explicitly.
Seven examples use batch_size=3. The positive-size guard passes. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does items[6:9] contain one item rather than three, and is any example dropped?
Read it this way: Seven items and batch size 3 yield lengths 3,3,1. The last slice keeps item 6 rather than dropping or duplicating it. Which real input identity disappears if the one-item final slice is discarded?

Advancing by the full batch size creates neither gaps nor duplicate positions. Only the final slice may be short.

Code

from collections.abc import Iterator, Sequence

def batches(items: Sequence, batch_size: int) -> Iterator[Sequence]:
   if batch_size <= 0:
      raise ValueError("batch_size must be positive")
   for start in range(0, len(items), batch_size):
      yield items[start : start + batch_size]

Cost: copied references overall; one yielded list needs storage. Retaining all batches takes storage. Validation runs when the generator advances, not when it is created.

Change the Requirement

Discard a Short Tail

New task: Yield full-width batches only.

Picture and change: Stop before a start whose full end exceeds the input length.

Code: Use the reference imports above.

def full_batches(items: Sequence, batch_size: int) -> Iterator[Sequence]:
   if batch_size <= 0:
      raise ValueError("batch_size must be positive")
   for start in range(0, len(items) - batch_size + 1, batch_size):
      yield items[start : start + batch_size]

Check: list(full_batches(list(range(7)), 3)) returns [[0,1,2], [3,4,5]].

Use when: A consumer explicitly requires fixed-width batches.

Accept a One-Pass Source

New task: Batch an iterable without indexing or a known length.

Picture and change: Consume at most one batch from the iterator at each step.

Code: This complete generator retains the short tail.

from collections.abc import Iterable
from itertools import islice

def stream_batches(items: Iterable, batch_size: int) -> Iterator[list]:
   if batch_size <= 0:
      raise ValueError("batch_size must be positive")
   iterator = iter(items)
   while batch := list(islice(iterator, batch_size)):
      yield batch

Check: list(stream_batches(iter([1,2,3]), 2)) returns [[1,2], [3]].

Use when: The source is one-pass or unbounded. Memory tracks one batch, excluding consumer retention.

Reconstruct

Why not average batch means equally when estimating the overall mean?

Reasoned answer

For batches [0,0] and [9], the unweighted batch-mean average is 4.5, but the example mean is 3. Weight each batch mean by its actual batch length. The short tail represents fewer observations, not fewer valid examples.

The reference annotation permits other Sequence implementations, but their indexing, slicing, copying, and view semantics may differ. The stated copying bounds and independent batch-container behavior apply to Python lists.