Advertisement
Advanced Python, Comprehensions & Generators

How would you implement a memory-efficient sliding window or batching generator over a large iterable?

Short answer

Use itertools.islice() combined with a generator function (or the itertools 'batched' recipe/function in newer Python) to pull a fixed-size chunk from the source iterator at a time, yielding each batch as a tuple or list — advancing through the source lazily without ever holding…

Save Python mock interview
Advertisement
AModel answer
Use itertools.islice() combined with a generator function (or the itertools 'batched' recipe/function in newer Python) to pull a fixed-size chunk from the source iterator at a time, yielding each batch as a tuple or list — advancing through the source lazily without ever holding the FULL dataset in memory.
from itertools import islice

def batched(iterable, size):
    it = iter(iterable)
    while batch := tuple(islice(it, size)):
        yield batch

for batch in batched(range(10), 3):
    print(batch)  # (0,1,2), (3,4,5), (6,7,8), (9,)
Real-world example
Processing a huge dataset (like database rows or log lines) in fixed-size batches for bulk API calls or bulk inserts.
Likely follow-ups
  • How does the walrus operator (:=) inside the while loop's condition make this batching implementation more concise?
Related topics