How to Split a List Into Even Chunks in Python

python_tutorials

Introduction

Splitting strings and lists are common programming activities in Python and other languages. Sometimes we have to split our data in peculiar ways, but more commonly – into even chunks.

The language does not have a built-in function to do this and in this tutorial, we’ll take a look at how to split a list into even chunks in Python.

For most cases, you can get by using generators:

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

Though, there are other interesting ways to do this, each with their own pros and cons!

Split a List Into Even Chunks of N Elements

A list can be split based on the size of the chunk defined. This means that we can define the size of the chunk. If the subset of the list doesn’t fit in the size of the

 

 

To finish reading, please visit source site