How do you split a list into evenly sized chunks in Python?

PythonServer Side ProgrammingProgramming

The easiest way to split list into equal sized chunks is to use a slice operator successively and shifting initial and final position by a fixed number.

In following example, a list with 12 elements is present. We split it into 3 lists each of length 4

l=[10,20,30,40,50,60,70,80,90,100,110,120]
x=0
y=12
for i in range(x,y,4):
x=i
print (l[x:x+4])


[10, 20, 30, 40]
[50, 60, 70, 80]
[90, 100, 110, 120]
raja
Published on 01-Jan-2018 19:24:44
Advertisements