Split list in to chunks of size n in Python

How to split list in to chunks of size n in Python ?

This tutorial guides you on how to split list in to chunks of size n in Python. Let’s learn two approaches: yield and list comprehension using which you can split list in to equal chunks of size n.

Split list in to chunks of size n in Python

Split list in to chunks of size n in Python

Let’s say the given input list is my_list. And you wanted to split list in to chunks of size n.

my_list = ['apple', 'boy', 'cat', 'dog', 'elephant', 'frog', 'goat', 'hen', 'ink', 'jug', 'kite', 'lion']

yield method

Below function can be used to achieve this. In this function we are using yield statement.

The yield statement is only used when defining generator function. Using this yield statement it is sufficient to cause the function definition split_chunks to create a generator function instead of a normal function.

That is, when this statement is used, it suspends the function execution and sends the value back to the caller. Also, it retains the state where it left off and resume from there and continue the function execution immediately after the last yield run.

Therefore, the yield statement is capable of generating series of values over the time.

def split_chunks(li,n):
    for i in range(0, len(li), n):
        yield li[i:i + n]

Hence, yield could split the list and generate values as shown below. Therefore, yield is called as Python generators.

n=3
chunks = list(split_chunks(my_list,n))
print(chunks)

[['apple', 'boy', 'cat'], ['dog', 'elephant', 'frog'], ['goat', 'hen', 'ink'], ['jug', 'kite', 'lion']]

Note, you may get the following error TypeError: ‘list’ object is not callable. In that case you need to delete the name list from global namespace to avoid such errors i.e., name shadowing.

To delete list from global namespace, run the following command.

# delete list from global namespace if required
del list

Using list comprehension

This is more elegant way of splitting the list in to chunks of size n by writing single line of code using list comprehension instead of writing a function like in the previous approach.

Here is an example, how to use list comprehension to split the given list in to equal size of chunks.

my_list = [10, 20, 30, 40, 50, 11, 22, 33, 44, 55, 66, 77]
n =3
chunks = [my_list[i:i + n] for i in range(0, len(my_list), n)]
print(chunks)

[[10, 20, 30], [40, 50, 11], [22, 33, 44], [55, 66, 77]]

That’s it. You had learnt how to split the given list in to equal chunks of size n.

Hope this is helpful 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments