pysnippets.lists.chunk_into_n
Split a list into n chunks
chunk_into_n(items: Sequence[T], n: int) -> list[list[T]]
Split a sequence into exactly n lists whose sizes differ by at most one.
You have 10 jobs and 3 workers. You want 3 piles that are as even as possible, not piles of 4, 4 and 2.
chunk_into_n.py✓ ruff · mypy --strict
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar("T")
def chunk_into_n(items: Sequence[T], n: int) -> list[list[T]]:
"""Split ``items`` into ``n`` lists whose sizes differ by at most one."""
if n < 1:
raise ValueError(f"n must be at least 1, got {n}")
size, extra = divmod(len(items), n)
chunks = []
start = 0
for i in range(n):
end = start + size + (i < extra)
chunks.append(list(items[start:end]))
start = end
return chunks- the first
extrachunks get one more item
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> chunk_into_n([1, 2, 3, 4, 5, 6, 7], 4)[[1, 2], [3, 4], [5, 6], [7]]passed on Python 3.11 to 3.14: >>> chunk_into_n([1, 2, 3, 4, 5], 4)[[1, 2], [3], [4], [5]]passed on Python 3.11 to 3.14: >>> chunk_into_n([1, 2], 3)[[1], [2], []]Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
divmodgives the basesizeand theextraitems left over.- The first
extrachunks take one more item.i < extrais a bool, andTrueadds as 1. - The result always has exactly
nlists. When there are fewer items than chunks, the last ones are empty.
Complexity: O(n) time, O(n) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.lists.chunk_into_n import chunk_into_nNo dependencies: copy chunk_into_n.py into your project, or clone the repo.Adapted from chunk-into-n in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Rewritten: balanced sizes, always n chunks, typed, validates n. Suggest an edit.