Iterating in Fixed-Size Chunks

Concepts covered: Two-Pointer

Why data moves in batches

Most systems that receive data cap how much they accept per call: a bulk insert takes a limited number of rows per statement, and an HTTP API takes a limited number of records per request. One row per call pays a network round trip for every row, and everything in 1 call gets rejected. A batch loop hands the data over in groups of a fixed size. It also has to decide what happens to the rows left over when the total does not divide evenly.

Batch boundaries from a range step

When the data is a list of known length, range(0, total_rows, batch_size) produces each batch's first index. The end is the start plus the batch size. When that would run past the total, the end is pulled back to the total.

total_rows = 10
batch_size = 4

for start in range(0, total_rows, batch_size):
    end = start + batch_size
    if end > total_rows:
        end = total_rows
    print("batch rows", start, "to", end - 1, "size", end - start)

Output:

batch rows 0 to 3 size 4
batch rows 4 to 7 size 4
batch rows 8 to 9 size 2

Stepping by 4 from 0 gives 3 starts, the last at 8. For the third batch, start + batch_size is 12, past the 10 rows that exist, so the clamp sets end to 10 and the batch holds 2 rows. Without the clamp, code that reads rows up to end - 1 would ask for row 10 and raise an IndexError.

To know the batch count in advance, divide the total by the size and round up. Floor division rounds down, so add batch_size - 1 first: (10 + 4 - 1) // 4 is 13 // 4, which is 3. When the total divides evenly, the added amount falls short of the next multiple, so (12 + 3) // 4 is still exactly 3.

This loop splits 13 rows into batches of 5. Where does the last batch start, and how many rows does it hold?

total_rows = 13
batch_size = 5

for start in range(0, total_rows, batch_size):
    end = start + batch_size
    if end > total_rows:
        end = total_rows
    print(start, end - start)

The accumulator: batches from any iterable

A range step needs the length up front. A generator, a file read line by line, or a stream of events has no length until it ends. The accumulator form handles all of these sources. It appends each item to a batch list, and when the list reaches the batch size, it hands the list off and starts a new empty one. batch.append(event) adds 1 item to the end of the list, and len(batch) counts its items.

events = ["e1", "e2", "e3", "e4", "e5", "e6", "e7"]
batch_size = 3
batch = []

for event in events:
    batch.append(event)
    if len(batch) == batch_size:
        print("send", batch)
        batch = []

if batch:
    print("send", batch)
send ['e1', 'e2', 'e3']
send ['e4', 'e5', 'e6']
send ['e7']

When the for loop ends, batch still holds 'e7', which never reached size 3. The if batch: check relies on truthiness: an empty list is falsy, so the final send runs only when items are left over. With 6 events, the second send would empty the list and the check would skip.

Packaging the accumulator as a generator

A generator function packages the accumulator, so every batch loop becomes a single for batch in batches(...) line and the tail is handled in 1 place. def batches(items, size): names a reusable block of code that takes 2 inputs. Each yield batch hands 1 batch to the for loop that asked for it and pauses there. When the loop asks for the next batch, the code resumes on the line after the yield.

def batches(items, size):
    batch = []
    for item in items:
        batch.append(item)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch


for batch in batches(range(1, 11), 4):
    print(batch)

Output:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10]

The input here is a range, and the generator never asks for its length, so the same code batches anything you can loop over, including a file or another generator. The generator yields lazily, so only 1 batch sits in memory at a time while the job pages through millions of rows.

This loop collects 11 order IDs in batches of 4 and has no flush after it. What does it print?

order_ids = [101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
batch = []
for order_id in order_ids:
    batch.append(order_id)
    if len(batch) == 4:
        print("sent", len(batch))
        batch = []
print("unsent", len(batch))

About this lesson

This section is part of the Loops: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.