You can try something like:
In [13]: l = [1,2,3,4,5,6,7,8]
In [14]: result = [l[i:i+3] for i in xrange(0, len(l), 3)]
In [15]: result
Out[15]: [[1, 2, 3], [4, 5, 6], [7, 8]]
This pulls out slices from the list that are of length n
, where n
is the number that you add to i
and is also the step value in your range
. As @Eric pointed out, this breaks the list into chunks of three, but not three chunks. In order to get it into three chunks, you can do something like:
In [21]: l = [1,2,3,4,5,6,7,8]
In [22]: chunk = int(round(len(l)/3.0))
In [23]: result = [l[i:i+chunk] for i in range(0,len(l),chunk)]
In [24]: result
Out[24]: [[1, 2, 3], [4, 5, 6], [7, 8]]
In [25]: l = [1,2,3,4,5]
In [26]: chunk = int(round(len(l)/3.0))
In [27]: result = [l[i:i+chunk] for i in range(0,len(l),chunk)]
In [28]: result
Out[28]: [[1, 2], [3, 4], [5]]
As it sounds like you have certain constraints, this could be written in a for
loop as well (although this actually has more function calls than the one above :) ):
In [17]: result = []
In [18]: for i in xrange(0, len(l), 3):
....: result.append(l[i:i+3])
....:
....:
In [19]: result
Out[19]: [[1, 2, 3], [4, 5, 6], [7, 8]]