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
<div class="alert alert-info flex not-prose">![]()
<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.