How do I split a list of arbitrary length into equal sized chunks? See also: How to iterate over a list in chunks. To chunk strings, see Split string every nth character?

 

To split a list into equal-sized chunks, you can use various techniques such as list comprehensions, loops, or external libraries like numpy for more advanced scenarios. Here's an example using a simple loop to split a list into chunks:

python
def split_into_chunks(lst, chunk_size): for i in range(0, len(lst), chunk_size): yield lst[i:i + chunk_size] original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] chunk_size = 3 chunked_list = list(split_into_chunks(original_list, chunk_size)) print(chunked_list) # Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In this example, the split_into_chunks function takes the original list and a desired chunk_size as input. It uses a loop to iterate over the list and yield chunks of the specified size.

If you prefer a more concise approach, you can achieve the same result using list comprehensions:

python
chunked_list = [original_list[i:i + chunk_size] for i in range(0, len(original_list), chunk_size)]

Both of these approaches break the original list into equal-sized chunks of chunk_size.

Keep in mind that if the length of the list is not evenly divisible by the chunk_size, the last chunk will contain fewer elements.

Comments