fluttersmith/py-snippetsGitHub ↗

Split a list into n chunks

Split a sequence into exactly n lists whose sizes differ by at most one.

Lists#splittingO(n) time✓ 3 examples pass on 3.11–3.14

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
  1. the first extra chunks 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).

How it works

  • divmod gives the base size and the extra items left over.
  • The first extra chunks take one more item. i < extra is a bool, and True adds as 1.
  • The result always has exactly n lists. When there are fewer items than chunks, the last ones are empty.

Complexity: O(n) time, O(n) space

Importfrom 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.