/  Technology   /  How do you split a list into evenly sized chunks in Python?
How do you split a list into evenly sized chunks in Python

How do you split a list into evenly sized chunks in Python?

 

We are given a list of arbitrary lengths and our task is to split that list into equal sized chunks and should be able to operate on it. 

 

Let’s take an example to understand this scenario. We have a list with the following elements.

 

Example:

list= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

Output:

Now we have to divide these into, let’s say 4 equal parts, which means we have 20 elements that must be divided into 4 separate lists with 5 elements in each of them.

 

Example:

[1,2,3,4]
[5,6,7,8]
[9,10,11,12]
[13,14,15,16]
[17,18,19,20]

Output:

Approach 1:

We’ll write code for this task now. We have taken the list and stored the chunk size into a variable named ‘n’. We use a for loop to iterate our list and in the range() function we take in 3 arguments the first value 0 is the start value, the second value, len(list) is the stop value and the third value n is the step size, here chunk size(4). And use slicing operation on the list as 

Example:

(list[i:i+n])

Output:

 

Note: To learn more about the range() function, refer to this article: range() function

This is how our entire code looks like

Example:

list= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
n = 4

for i in range(0, len(list), n):
   print(list[i:i+n])

Output:

Approach 2:

Let’s now see the second approach that is using the yield keyword. 

To know more about the yield keyword, refer to this article

Example:

list= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
n = 4
def divide_into_chunks(list, length):
   for i in range(0, len(list0, length):
      yield list[i:i+length]


for chunk in divide_into_chunks(list, n):
   print(chunk)

Output:

The yield keyword interrupts the function and returns a value. Whenever the function gets called, it returns the next value and the function’s execution stops again. We use this behavior of yield in a for-loop, where we try to get a value from the generator with which we work inside the loop and finally repeat this with the next value.

 

Leave a comment