Python Program to Split a List Into Evenly Sized Chunks – 2024

Hey guys, in this blog we will see a Python Program to Split a List Into Evenly Sized Chunks.

Table of Contents

Example 1: Using yield

def split(list_a, chunk_size):

  for i in range(0, len(list_a), chunk_size):
    yield list_a[i:i + chunk_size]

chunk_size = 2
my_list = [1,2,3,4,5,6,7,8,9]
print(list(split(my_list, chunk_size)))


[[1, 2], [3, 4], [5, 6], [7, 8], [9]]

  • Using yield to print the results.
  • Chunk size is 2 so it will start like printing list_a[0:2] then list_a[2:4] then list_a[4:6] and so on…

Example 2: Using NumPy

import numpy as np

my_list = [1,2,3,4,5,6,7,8,9]
print(np.array_split(my_list, 5))


[array([1, 2]), array([3, 4]), array([5, 6]), array([7, 8]), array([9])]

  • Numpy has a built-in function that creates splits of an array using the array_split() method.
  • It just needs an array and a split size.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

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