Chunk an Iterable with itertools

Medium ⏱ 12 min 45% acceptance ★★★★★ 4.6
Write chunks(seq, size) returning a list of tuples, each holding up to size consecutive items, using itertools.islice over a shared iterator (the classic pre-3.12 way to batch — itertools.batched exists only in newer Pythons, so build it yourself here).

Examples

Example 1
Input
chunks([1, 2, 3, 4, 5], 2)
Output
[(1, 2), (3, 4), (5,)]
Explanation

Two full chunks and a final partial one.

Constraints

  • Use itertools.islice.
  • The last chunk may be short.

Topics

Modules & Packagesitertools

Companies

MetaMicrosoftBloomberg

Hints

Hint 1

it = iter(seq) once; islice(it, size) advances it.

Hint 2

Loop until islice yields an empty tuple.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.