Categories
Python Answers

How to split a list into evenly sized chunks with Python?

Spread the love

Sometimes, we want to split a list into evenly sized chunks with Python.

In this article, we’ll look at how to split a list into evenly sized chunks with Python.

How to split a list into evenly sized chunks with Python?

To split a list into evenly sized chunks with Python, we can use list comprehsion.

For instance, we write:

import pprint

lst = list(range(10, 55))
n = 10
chunked = [lst[i:i + n] for i in range(0, len(lst), n)]
pprint.pprint(chunked)

We create the lst list with numbers from 10 to 54.

Then we want to split them to chunks of 10, which we assigned to n.

Then we split the lst list into chunks of size n with:

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

We loop through the lst entries and compute the chunks with lst[i:i + n].

Therefore, chunked is:

[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54]]

Conclusion

To split a list into evenly sized chunks with Python, we can use list comprehsion.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *