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

How do you split a list into evenly sized chunks?

How do you split a list into evenly sized chunks?

 

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.

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.

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 

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

https://www.i2tutorials.com/whats-range-and-xrange-in-python/

This is how our entire code looks like

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: https://www.i2tutorials.com/what-does-the-yield-keyword-do/

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