Write a Python Program to Split a List Into Evenly Sized Chunks

Python Program to Split a List Into Evenly Sized Chunks

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn  Python programming concepts. You can learn Python language at your own speed and time. One can learn concepts of Python language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

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

Write a Python Program to Split a List Into Evenly Sized Chunks

PROGRAM: Python Program to Split a List Into Evenly Sized Chunks

/* Python Program to Split a List Into Evenly Sized Chunks */

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)))

Output

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

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))

Output

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

Leave a Reply

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