Batching and Right-Padding Variable-Length Sequences

Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen

Problem Statement

Training or running inference on sequence models requires turning ragged, uneven-length feature vectors into rectangular 2D mini-batches. Implement batch_and_pad to group an ordered list of floating-point sequences into batches and right-pad shorter rows within each batch:

def batch_and_pad(
    sequences: list[list[float]],
    batch_size: int,
    pad_value: float = 0.0,
    drop_last: bool = False,
) -> list[list[list[float]]]:
    ...

Rules

  1. Sequential Grouping: Preserve input order and split sequences into consecutive chunks containing batch_size sequences each (except possibly the final chunk when len(sequences) is not divisible by batch_size).
  2. Trailing Partial Chunk (drop_last): When drop_last is True and the last chunk has strictly fewer than batch_size sequences, omit that chunk from the result. Otherwise (when drop_last is False, or when the last chunk already has batch_size sequences), keep it.
  3. Per-Batch Right Padding: Independently for each retained chunk, let max_len equal the length of the longest sequence inside that chunk. Extend every shorter sequence in that chunk on the right using copies of pad_value so all rows in the chunk share length max_len. Do not mutate the caller's input lists.
  4. Zero-Length Sequences: An empty list [] is a valid sequence of length 0. If every sequence inside a retained chunk is [], its max_len is 0 and each row in that chunk stays []. If sequences itself is empty, return [].

Examples

Example 1

sequences = [[2.5], [4.0, 1.5, 3.0], [], [8.0, 6.0], [9.5]]
batch_size = 3
pad_value = 0.0
drop_last = False

batch_and_pad(sequences, batch_size, pad_value, drop_last)
# Output:
# [
#   [[2.5, 0.0, 0.0], [4.0, 1.5, 3.0], [0.0, 0.0, 0.0]],
#   [[8.0, 6.0], [9.5, 0.0]]
# ]

Walk-through: - The first chunk holds [[2.5], [4.0, 1.5, 3.0], []] with lengths 1, 3, and 0. Its local width is 3, so [2.5] gains two trailing 0.0 entries and [] gains three. - The second chunk holds [[8.0, 6.0], [9.5]] (2 sequences < 3), which is retained because drop_last=False and padded to its own local width of 2 (unaffected by width 3 from the first chunk).

Example 2

sequences = [[10.0, 20.0], [30.0, 40.0, 50.0], [], [], [70.0]]
batch_size = 2
pad_value = -9.0
drop_last = True

batch_and_pad(sequences, batch_size, pad_value, drop_last)
# Output:
# [
#   [[10.0, 20.0, -9.0], [30.0, 40.0, 50.0]],
#   [[], []]
# ]

Walk-through: - Chunk 1 ([[10.0, 20.0], [30.0, 40.0, 50.0]]) has local width 3, so [10.0, 20.0] is right-padded with -9.0. - Chunk 2 ([[], []]) contains only empty sequences, so its local width is 0 and both rows stay []. - Chunk 3 ([[70.0]]) has only 1 sequence (< batch_size), so drop_last=True discards it.

Constraints

  • 0 <= len(sequences) <= 10^5
  • 0 <= len(seq) <= 5,000 for every seq in sequences
  • Total count of numbers across all input sequences does not exceed 10^6
  • 1 <= batch_size <= 10^4
  • pad_value is a finite float

Step-by-step walkthrough

  1. Understand the goal and input/output shapes

    Deep learning frameworks process examples in rectangular arrays called tensors, where every row inside a mini-batch must have the exact same width. Because raw feature sequences arrive with different lengths, we need a preprocessing step that groups consecutive sequences into batches and extends shorter rows on the right.

    Given sequences, batch_size, pad_value, and drop_last, batch_and_pad returns a 3D list batches in which each item is one rectangular 2D batch:

    Input sequences:  [ [2.5],  [4.0, 1.5, 3.0],  [],  [8.0, 6.0],  [9.5] ]
                      |---------- batch 0 ----------|  |---- batch 1 ----|
    
    batch_size = 3, pad_value = 0.0, drop_last = False:
      batch 0: lengths [1, 3, 0] -> width = 3 -> [ [2.5, 0.0, 0.0], [4.0, 1.5, 3.0], [0.0, 0.0, 0.0] ]
      batch 1: lengths [2, 1]    -> width = 2 -> [ [8.0, 6.0], [9.5, 0.0] ]  (dropped if drop_last=True)
    

    Four invariants govern the output: - Order stays intact: indices 0 .. batch_size - 1 form batch 0, the next batch_size form batch 1, and so on. - Strictly undersized final chunk: drop_last=True discards the trailing chunk only when its length is strictly below batch_size (<, never <=). - Per-batch width: each batch pads solely to the widest sequence inside that batch, unaffected by wider sequences elsewhere. - Zero-length sequences remain valid: [] has length 0. When every sequence in a batch is [], its target width is 0 and every row remains [].

  2. Why batch-local two-pass processing is optimal

    A naive implementation might compute the maximum sequence length once across the entire input list and pad every batch to that global width. If a single outlier sequence has length 5,000 while all other sequences have length 4, global padding inflates every batch by over 1,000x. Finding max_len separately inside each batch avoids any cross-batch bloat.

    Can we beat scanning each sequence reference and writing each output float once? No — every element in the returned 3D list must be allocated and filled at least once. With n input sequences and P total floats across all returned batches (real entries plus filler), O(n + P) time is the theoretical floor, provided we avoid quadratic operations or mutating the caller's lists.

  3. Partition sequences into fixed-count chunks

    Python's range(0, len(sequences), batch_size) yields the starting offset start_idx of each chunk: 0, batch_size, 2 * batch_size, and so forth. Slicing sequences[start_idx : start_idx + batch_size] clamps cleanly at len(sequences) without raising an IndexError on a short trailing chunk.

    len(sequences) = 5, batch_size = 3:
      start_idx = 0 -> sequences[0:3] -> 3 items (full)
      start_idx = 3 -> sequences[3:6] -> 2 items (short: len < batch_size)
    

    Only the very last slice can ever satisfy len(raw_batch) < batch_size. Consequently, when drop_last is True and len(raw_batch) < batch_size, we can break immediately. We also validate batch_size >= 1 up front with a clear ValueError.

    def batch_and_pad(
        sequences: List[List[float]],
        batch_size: int,
        pad_value: float = 0.0,
        drop_last: bool = False,
    ) -> List[List[List[float]]]:
        if batch_size < 1:
            raise ValueError("batch_size must be at least 1")
    
        # batches: 3D list of padded 2D batches, shape [num_batches][rows_in_batch][L_max_of_batch]
        batches = []
    
        # Step through `sequences` in contiguous chunks of size `batch_size`.
        for start_idx in range(0, len(sequences), batch_size):
            raw_batch = sequences[start_idx : start_idx + batch_size]
    
            # Only the final slice can have strictly fewer than `batch_size` sequences;
            # a full final batch has len(raw_batch) == batch_size and is kept even when drop_last=True.
            if drop_last and len(raw_batch) < batch_size:
                break
    
            batches.append(pad_batch(raw_batch, pad_value))
    
        return batches
    
  4. Right-pad a single batch without mutating inputs

    Inside pad_batch(batch, pad_value), we run two simple loops over batch:

    1. Compute max_len: Initialize max_len = 0 and raise it whenever len(seq) > max_len. Starting at 0 naturally leaves max_len = 0 for an all-empty batch ([[], []]) with no extra branching.
    2. Construct each padded row: Set missing_count = max_len - len(seq), copy the original row via list(seq), and concatenate [pad_value] * missing_count on the right.

    Why call list(seq) even when missing_count == 0? - Mutating seq in place with .extend(...) would corrupt the caller's sequences argument. - Reusing seq directly without copying creates an alias (two variables referencing the exact same list object in memory), so any later edit to the output batch would silently alter the caller's input.

    def pad_batch(batch: List[List[float]], pad_value: float) -> List[List[float]]:
        """Right-pad every sequence in a single batch up to that batch's maximum length."""
        # Phase 1: Find L_max across this batch only (starts at 0 so all-empty batches get 0).
        max_len = 0
        for seq in batch:
            if len(seq) > max_len:
                max_len = len(seq)
    
        # Phase 2: Build a fresh padded row for every sequence without mutating the caller's lists.
        # padded_batch: 2D list of shape [len(batch)][max_len]
        padded_batch = []
        for seq in batch:
            missing_count = max_len - len(seq)
            # Always copy `seq` with `list(seq)` even when missing_count == 0, so mutating
            # the returned batch later can never mutate the original input sequence.
            padded_row = list(seq) + [pad_value] * missing_count
            padded_batch.append(padded_row)
        return padded_batch
    
  5. Walk through Examples 1 and 2

    First trace Example 1 (sequences = [[2.5], [4.0, 1.5, 3.0], [], [8.0, 6.0], [9.5]], batch_size = 3, pad_value = 0.0, drop_last = False):

    start_idx = 0 -> raw_batch = [[2.5], [4.0, 1.5, 3.0], []]
      max_len = max(1, 3, 0) = 3
      seq [2.5]           -> missing 2 -> [2.5, 0.0, 0.0]
      seq [4.0, 1.5, 3.0] -> missing 0 -> [4.0, 1.5, 3.0]
      seq []              -> missing 3 -> [0.0, 0.0, 0.0]
    
    start_idx = 3 -> raw_batch = [[8.0, 6.0], [9.5]]
      len(raw_batch) == 2 < 3, drop_last is False -> keep!
      max_len = max(2, 1) = 2
      seq [8.0, 6.0]      -> missing 0 -> [8.0, 6.0]
      seq [9.5]           -> missing 1 -> [9.5, 0.0]
    
    Result: [ [[2.5, 0.0, 0.0], [4.0, 1.5, 3.0], [0.0, 0.0, 0.0]],
              [[8.0, 6.0], [9.5, 0.0]] ]
    

    Now trace Example 2 (sequences = [[10.0, 20.0], [30.0, 40.0, 50.0], [], [], [70.0]], batch_size = 2, pad_value = -9.0, drop_last = True): - start_idx = 0: [[10.0, 20.0], [30.0, 40.0, 50.0]] pads to width 3 -> [[10.0, 20.0, -9.0], [30.0, 40.0, 50.0]]. - start_idx = 2: [[], []] has max_len = 0 -> [[], []]. - start_idx = 4: [[70.0]] has length 1 < 2 with drop_last=True, triggering break and omitting the trailing chunk.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def pad_batch(batch: List[List[float]], pad_value: float) -> List[List[float]]:
        """Right-pad every sequence in a single batch up to that batch's maximum length."""
        # Phase 1: Find L_max across this batch only (starts at 0 so all-empty batches get 0).
        max_len = 0
        for seq in batch:
            if len(seq) > max_len:
                max_len = len(seq)
    
        # Phase 2: Build a fresh padded row for every sequence without mutating the caller's lists.
        # padded_batch: 2D list of shape [len(batch)][max_len]
        padded_batch = []
        for seq in batch:
            missing_count = max_len - len(seq)
            # Always copy `seq` with `list(seq)` even when missing_count == 0, so mutating
            # the returned batch later can never mutate the original input sequence.
            padded_row = list(seq) + [pad_value] * missing_count
            padded_batch.append(padded_row)
        return padded_batch
    
    
    def batch_and_pad(
        sequences: List[List[float]],
        batch_size: int,
        pad_value: float = 0.0,
        drop_last: bool = False,
    ) -> List[List[List[float]]]:
        if batch_size < 1:
            raise ValueError("batch_size must be at least 1")
    
        # batches: 3D list of padded 2D batches, shape [num_batches][rows_in_batch][L_max_of_batch]
        batches = []
    
        # Step through `sequences` in contiguous chunks of size `batch_size`.
        for start_idx in range(0, len(sequences), batch_size):
            raw_batch = sequences[start_idx : start_idx + batch_size]
    
            # Only the final slice can have strictly fewer than `batch_size` sequences;
            # a full final batch has len(raw_batch) == batch_size and is kept even when drop_last=True.
            if drop_last and len(raw_batch) < batch_size:
                break
    
            batches.append(pad_batch(raw_batch, pad_value))
    
        return batches
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine packing wooden planks of uneven lengths into rectangular shipping crates that each hold batch_size planks. A crate does not need to be as long as the longest plank in the entire warehouse — it only needs to match the longest plank placed inside that specific crate (max_len). For any shorter plank in that crate, you fill the empty space on its right end with foam spacers (pad_value) so nothing slides around, and if the very last crate is only partially full, drop_last=True tells you to set that incomplete crate aside instead of shipping it. In machine learning pipelines, grouping examples into fixed-count chunks is called batching (processing several inputs together in parallel on hardware accelerators), and extending shorter rows at the end to form a rectangle is called right padding.

Why do simpler shortcuts go wrong? If you pad every sequence to the global maximum length across the whole dataset, a single 5,000-step sequence forces thousands of tiny 3-step sequences in completely unrelated batches to expand to length 5,000, wasting huge amounts of memory and compute. On the other hand, if you append pad_value directly onto the input lists using .extend(), you permanently corrupt the caller's dataset so it can never be reused in a second training epoch.

Let's trace Example 1 (sequences = [[2.5], [4.0, 1.5, 3.0], [], [8.0, 6.0], [9.5]], batch_size = 3, pad_value = 0.0, drop_last = False):

Chunk 1 (indices 0..2): [[2.5], [4.0, 1.5, 3.0], []]
  -> lengths are 1, 3, and 0 -> max_len = 3
  -> right-pad to 3: [[2.5, 0.0, 0.0], [4.0, 1.5, 3.0], [0.0, 0.0, 0.0]]

Chunk 2 (indices 3..4): [[8.0, 6.0], [9.5]]
  -> 2 sequences (< batch_size 3), kept because drop_last is False
  -> lengths are 2 and 1 -> max_len = 2
  -> right-pad to 2: [[8.0, 6.0], [9.5, 0.0]]

Complexity

Let n be len(sequences) and P be the total number of floats across all returned batches (original values plus appended pad_value entries).

  • Time: O(n + P). Stepping across sequences in chunks of batch_size and checking len(seq) visits each of the n sequence references a constant number of times, and constructing the copied + padded rows writes each of the P output floats once (plus at most O(n) skipped sequence references if drop_last=True discards the trailing chunk, which is absorbed into O(n)).
  • Space: O(P) for the output (O(batch_size) auxiliary space). Aside from the returned 3D batches list holding P floats, raw_batch holds at most batch_size list references at a time.

Notice why we express time and memory in terms of P rather than total input elements alone: P depends on how lengths are distributed inside each batch. Under the constraints (n = 10^5, batch_size = 10^4, max sequence length 5,000, total input elements <= 10^6), 10 batches each containing one length-5,000 sequence and 9,999 empty sequences have only 5 * 10^4 input floats yet require 10 * 10^4 * 5,000 = 5 * 10^8 output floats! That gap is inherent to rectangular batching and motivates lazy streaming and length bucketing in the follow-ups.

Edge cases

  • Empty sequences ([]): range(0, 0, batch_size) runs zero iterations, returning [] whether drop_last is True or False.
  • Fewer sequences than batch_size (0 < n < batch_size): Produces a single short batch when drop_last=False, or [] when drop_last=True.
  • Exact multiple (n % batch_size == 0): Every slice has length batch_size, so len(raw_batch) < batch_size is never true and drop_last=True discards nothing.
  • batch_size == 1: Every sequence forms its own full 1-row batch with max_len = len(seq), so zero padding is added and nothing is dropped.
  • Batch of only empty sequences ([[], []] in Example 2): max_len starts at 0 and stays 0, returning [[], []] with zero pad_value elements appended.
  • Empty sequence paired with non-empty sequences ([[2.5], [4.0, 1.5, 3.0], []]): [] has length 0 and expands cleanly into [pad_value, pad_value, pad_value].
  • Invalid batch_size < 1: Raises a descriptive ValueError instead of letting range(..., 0) fail with a step-size error or letting negative steps return [] silently.

Common mistakes

  • Dropping the final batch unconditionally when drop_last=True: Writing if drop_last: batches.pop() throws away a completely full last batch whenever len(sequences) is an exact multiple of batch_size. Always check len(raw_batch) < batch_size.
  • Padding to the global maximum length: Computing max_len once across all of sequences instead of inside each batch gives wrong widths on batches whose local maximum is smaller, failing Example 1 ([[8.0, 6.0], [9.5, 0.0]] has width 2, not 3).
  • Mutating or aliasing input sequences: Using seq.extend(...) mutates the caller's input in place, and appending seq directly when len(seq) == max_len aliases the caller's list so later in-place edits to the output also change the input. Always copy with list(seq).
  • Calling max(len(s) for s in batch) without default=0 in reusable helpers: While stride slicing never hands pad_batch an empty batch, reusable helpers in streaming pipelines can encounter empty chunks; starting max_len = 0 (or passing default=0) avoids ValueError: max() arg is an empty sequence.
  • Left-padding instead of right-padding: Writing [pad_value] * missing_count + list(seq) shifts every original element's index to the right, breaking positional alignment.

Follow-up questions

  • How can you convert this function into a lazy iterator so arbitrarily large sequence streams can be batched in bounded memory? Turn the function into a generator (a Python function that uses yield to produce one batch on demand rather than materializing every batch in RAM at once) and pull chunks of batch_size items from iter(sequences) via itertools.islice. That allows sequences to be an unbounded disk or network stream and lowers peak memory from O(P) across the entire dataset to O(batch_size * max_len) for the single batch currently yielded.

```python from itertools import islice

def stream_batches(sequences, batch_size, pad_value=0.0, drop_last=False): if batch_size < 1: raise ValueError("batch_size must be at least 1") iterator = iter(sequences) while True: raw_batch = list(islice(iterator, batch_size)) if not raw_batch or (drop_last and len(raw_batch) < batch_size): return yield pad_batch(raw_batch, pad_value) ```

  • What changes are required to emit a companion attention mask alongside each batch distinguishing original entries from appended filler values? Alongside each padded_row, construct [1] * len(seq) + [0] * missing_count as an attention mask (a binary indicator matrix telling downstream layers which positions carry real observations versus synthetic padding). This is crucial whenever pad_value (such as 0.0) can also occur naturally inside real input vectors, because a model cannot tell real 0.0 measurements apart from padded 0.0 slots without an explicit mask.

python def pad_batch_with_mask(batch, pad_value=0.0): max_len = max((len(seq) for seq in batch), default=0) padded_batch = [] mask_batch = [] for seq in batch: missing_count = max_len - len(seq) padded_batch.append(list(seq) + [pad_value] * missing_count) mask_batch.append([1] * len(seq) + [0] * missing_count) return padded_batch, mask_batch

  • When a dataset mixes very short sequences with occasional multi-thousand-step outliers, how can length bucketing cut down padding overhead without sacrificing training randomness? Apply pooled length bucketing (grouping sequences of similar lengths prior to batching so each batch's local max_len stays close to its members' true lengths). At the start of each epoch, shuffle the dataset, partition it into medium-sized windows (such as 50 * batch_size sequences per window), sort within each window by len(seq) with small random tie-breaking jitter, slice each window into batch_size mini-batches, and shuffle the mini-batch order before training. Long outliers get packed together into one or two wide batches rather than stretching dozens of short batches, while cross-epoch shuffling keeps stochastic gradient updates unbiased.

Follow-up questions

Similar questions

More Siemens interview questions

All 5 Siemens questions →