Sequence Padding: Trim the Long, Fill the Short

NLPMedium+20 XP+15

Sequence Padding: Trim the Long, Fill the Short

Sentences have different lengths. Matrices don't. Every NLP pipeline hits this wall immediately, and the fix is always the same: pick one length and force every sequence to match it.

Task: write pad_sequences(sequences, max_len, pad_value) that returns a list where every inner list has exactly max_len items.

  • Sequences shorter than max_len get pad_value appended until they fit.
  • Sequences longer than max_len are cut off at max_len.
  • Both operate at the end of the sequence — keep the front, pad or trim the back.
  • An empty list of sequences returns an empty list.

Which end you pad is a real modelling decision, not a detail. A plain RNN reading left to right finishes on whatever came last, so trailing pad tokens are the final thing it sees — which is exactly why front-padding used to be the norm.

Examples

sequences = [[1, 2, 3], [4], [5, 6]]
max_len = 3
pad_value = 0
returns [[1, 2, 3], [4, 0, 0], [5, 6, 0]]
sequences = [[1, 2, 3, 4, 5], [7, 8]]
max_len = 3
pad_value = 0
returns [[1, 2, 3], [7, 8, 0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run