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
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?
Sources and provenance
Full interview answer 10 min read
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
Yield the first half-open slicestart=0 yields items[0:3]=[0,1,2]. Index 3 is excluded.
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
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
Yield the first half-open slicestart=0 yields items[0:3]=[0,1,2]. Index 3 is excluded.
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, Sequencedef 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:O(n) copied references overall; one yielded list needs O(min(n,batch_size)) storage.
Retaining all batches takes O(n) 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]
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.