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
- Validates that the chunk size is positive.
- Slices the list every
sizeelements inside a list comprehension. - Returns the slices as a list of chunks.
Keywords and builtins used here
chunkdefforiflenraiserangereturn
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.
Step 4 of 10 in Collections, step 26 of 72 in Language basics.