Categories
Python Answers

How to split a list into N parts of approximately equal length with Python?

Spread the love

Sometimes, we want to split a list into N parts of approximately equal length with Python.

In this article, we’ll look at how to split a list into N parts of approximately equal length with Python.

How to split a list into N parts of approximately equal length with Python?

To split a list into N parts of approximately equal length with Python, we can use list comprehension.

For instance, we write:

def chunkify(lst, n):
    return [lst[i::n] for i in range(n)]


chunks = chunkify(list(range(13)), 3)
print(chunks)

We define the chunkify function to split the lst list into n chunks.

To do this, we use list comprehension to return slices of list with from index i to the end with n items in each chunk.

Then we call chunkify with the list(range(13)) list and 3 to divide the list into 3 chunks.

Therefore, chunks is [[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]].

Conclusion

To split a list into N parts of approximately equal length with Python, we can use list comprehension.

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 *