Python problem 14 of 30

Chunk a list

  • Python
  • Medium

Write chunks(xs, n) that splits a list into pieces of length n. The last piece may be shorter.

chunks([1, 2, 3, 4, 5], 2)   # [[1, 2], [3, 4], [5]]
chunks([1, 2, 3], 5)         # [[1, 2, 3]]
chunks([], 3)                # []
Show hint

range(0, len(xs), n) gives you the start index of every chunk. Slicing past the end of a list is not an error.

Show solution
def chunks(xs, n):
    return [xs[i:i + n] for i in range(0, len(xs), n)]

Each start index jumps by n, and the slice xs[i:i + n] quietly stops at the end of the list, which handles the short last chunk. Python 3.12 added itertools.batched(xs, n), which does the same but gives tuples.

Want a problem like this every day? See today's problem and keep a streak going.