Split a List Into Evenly Sized Chunks in Python Using List Comprehension

(Last Updated On: 13/02/2023)

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

# Split a List Into Evenly Sized Chunks in Python Using List comprehension

my_list =  [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
 
# How many elements each
# list should have
n = 4
 
# using list comprehension
final = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )]
print (final) 

Output:

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

Leave a Reply

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