Split a list into chunks
Splits any list into fixed-size chunks using a slicing generator, so the last chunk can be shorter without any special-case code.
Last updated
def chunk_list(items, size):
for i in range(0, len(items), size):
yield items[i:i + size]
# list(chunk_list([1, 2, 3, 4, 5], 2)) -> [[1, 2], [3, 4], [5]]How it works
range(0, len(items), size) walks the start index of each chunk in steps of size (0, 2, 4, ... for size=2), and Python slicing (items[i:i+size]) is naturally forgiving about running past the end of the list — it just returns however many elements are left, which is exactly why the last chunk comes out shorter with no extra logic.
It's written as a generator (yield, not return a list of lists) so chunking a very large list doesn't build every chunk in memory upfront — chunks are produced one at a time as the caller iterates, and list(...) at the call site is what materializes them when you actually want the full list.
Edge cases to know
- →size <= 0 causes range() to either loop forever (size negative, combined with a positive stop) or raise nothing useful — validate size > 0 before calling if it isn't a hard-coded constant.
- →The input needs to support slicing (lists, tuples, strings); a plain iterator or generator passed as items won't work since items[i:i+size] requires random access.
- →This only handles one level — chunking, not flattening. It works on any sliceable sequence type, not just lists, despite the name.