One of the ways of doing it is
>>> l = ['a','b','c','d','e','f','g','h','i','j']
>>> [l[i:i+4] for i in range(0,len(l),3)]
[['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['g', 'h', 'i', 'j'], ['j']]
Here :
l[i:i+4]
implies that we print a chunk of 4 values starting from position i
range(0,len(l),3)
implies that we traverse the length of the list by taking three jumps
So the basic working of this is that, we are taking a chunk of 3 elements from the list, but we are modifying the slice length so that it includes an additional element. In this way, we can have a list of 4 elements.
Small Note - The initialization oldList=[a,b,c,d,e,f,g,h,i,j,...]
is invalid unless a
,b
,c
,d
,etc are previously defined. You were perhaps looking for oldList = ['a','b','c','d','e','f','g','h','i','j']
Alternatively, if you wanted a solution which would split into even sized chunks only, then you could try this code :-
>>> [l[i:i+4] for i in range(0,len(l)-len(l)%4,3)]
[['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['g', 'h', 'i', 'j']]