typestar

Chunk a list in Python

Batching a list into fixed-size pieces - a staple for pagination and APIs.

def chunk(items, size):
    if size < 1:
        raise ValueError("size must be positive")
    return [items[i:i + size] for i in range(0, len(items), size)]

How it works

  1. Validates that the chunk size is positive.
  2. Slices the list every size elements inside a list comprehension.
  3. Returns the slices as a list of chunks.

Keywords and builtins used here

The run, in numbers

Lines
4
Characters to type
141
Tokens
45
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 30 seconds.

Type this snippet

Step 4 of 10 in Collections, step 26 of 72 in Language basics.

← Previous Next →