W3docs

How do I split a list into equally-sized chunks?

Here is a function that takes a list and an integer n and splits the list into n equally sized chunks:

Here is a function that takes a list and an integer chunk_size and splits the list into equally-sized chunks:

Split a list into equally-sized chunks in Python

def split_list(input_list, chunk_size):
    if chunk_size <= 0:
        raise ValueError("chunk_size must be a positive integer")
    # Iterate over the list with a step equal to chunk_size
    for i in range(0, len(input_list), chunk_size):
        # Use slicing to get the current chunk
        yield input_list[i : i + chunk_size]

# Test the function
input_list = [1, 2, 3, 4, 5, 6, 7, 8]
for sublist in split_list(input_list, 3):
    print(sublist)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

This will output:

[1, 2, 3]
[4, 5, 6]
[7, 8]

The function uses the yield keyword to return a generator that produces the sublists. This means that the function will not create a new list with all of the sublists in it, but rather it will allow you to iterate over the sublists and do something with them one at a time. This can be more memory efficient if the input list is very large and you don't want to store all of the sublists in memory at once.