Split a List Into Evenly Sized Chunks in Python Using itertool

(Last Updated On: 16/02/2023)

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

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

from itertools import islice

def chunk(arr_range, arr_size):
	arr_range = iter(arr_range)
	return iter(lambda: tuple(islice(arr_range, arr_size)), ())

list(chunk(range(30), 5))

Output:

[(0, 1, 2, 3, 4),
 (5, 6, 7, 8, 9),
 (10, 11, 12, 13, 14),
 (15, 16, 17, 18, 19),
 (20, 21, 22, 23, 24),
 (25, 26, 27, 28, 29)]

Leave a Reply

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