Split a List Into Evenly Sized Chunks in Python Using Yield

(Last Updated On: 10/02/2023)

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

# Python Program to Split a List Into Evenly Sized Chunks Using Yield

my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
 
# Yield successive n-sized
# chunks from l.
def divide_chunks(l, n):
     
    # looping till length l
    for i in range(0, len(l), n):
        yield l[i:i + n]
 
# How many elements each
# list should have
n = 5

x = list(divide_chunks(my_list, n))
print (x)

Output:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]

Leave a Reply

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