Two Simple Algorithms for Chunking a List in Python
Convert a list to evenly sized segments
Published in
3 min readMay 16, 2020
The Challenge
Create a function that converts a list to a two-dimensional “list of lists” where each nested structure is a specified equal length.
Here are some example inputs and expected outputs:
# INPUT LIST: [1,2,3,4,5,6]
# INPUT SIZE: 3
# OUTPUT: [[1,2,3],[4,5,6]]# INPUT LIST: [1,2,3,4,5]
# INPUT SIZE: 2
# OUTPUT: [[1,2],[3,4],[5]]# INPUT LIST: [1,2,3]
# INPUT SIZE: 4
# OUTPUT: [[1,2,3]]
Reviewing our examples, there are some important distinctions for scenarios where the list and chunk size do not perfect match up.
- When the list does not evenly divide by the chunk size, the last index will be shorter than the evenly sized chunks.
- When the chunk size is larger than the list itself, a chunk will still be created with the list in the first index.
We’re going to solve this two ways. The first function will be written generically — using techniques that can be applied in any programming language. The second function will be optimized for Python — using techniques that are specific to the language.