Split records into batches

Python data engineering interview problem. Difficulty: beginner. Pattern: Arrays. About 10 minutes. Free to practice.

Cut a list of records into batches of a fixed size so a pipeline can load them one batch at a time. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A pipeline loads records into a database, but the database accepts only a few records per call. Implement make_batches(records, size). Return a list of batches. Each batch is a list of at most size records. Keep the records in their original order. Every batch is full except possibly the last one. An empty input gives an empty list.

Requirements

  • Batches keep the original order.
  • Only the last batch may be smaller than size.

Constraints

  • size is at least 1.
  • The input list is not changed.

Examples

Input: make_batches([1, 2, 3, 4, 5], 2) Output: [[1, 2], [3, 4], [5]] Five records in batches of two leave one record for the last batch.

Topics: lakebench, python, batch, chunk, pipeline.

More Python interview questions · All interview problems · Learn data engineering

beginner

Split records into batches

Interview-style drill: Cut a list of records into batches of a fixed size so a pipeline can load them one batch at a time.

A pipeline loads records into a database, but the database accepts only a few records per call. Implement `make_batches(records, size)`. - Return a list of batches. Each batch is a list of at most `size` records. - Keep the records in their original order. - Every batch is full except possibly the last one. - An empty input gives an empty list.