Python Principles
Python Q&A

How do you split up a list into chunks of the same size?


You can define a function that iterates over and collects the list elements. When the given chunk-size is reached, the chunk is appended to a result list. Here is code that does this:

def chunks(l, chunk_size):
    result = []
    chunk = []
    for item in l:
        if len(chunk) == chunk_size:
            chunk = []

    # don't forget the remainder!
    if chunk:

    return result

print(chunks([1, 2, 3, 4, 5], 2))

Running the code gives this output:

[[1, 2], [3, 4], [5]]

You can also use yield to turn the function into a generator.