1 Sep
2012
1 Sep
'12
10:02 p.m.
On 01/09/2012 18:16, Michele Lacchia wrote:
+ 1 for the lazy version. Why not using itertools.islice instead of the innermost for loop?
OK, here's a lazy version using islice: from itertools import islice def chunks(seq, size): '''Cut sequence into chunks of given size. If `seq` length is not divisible by `size` without reminder, last chunk will have length less than size. >>> list( chunks([1,2,3,4,5,6,7], 3) ) [[1, 2, 3], [4, 5, 6], [7]] ''' if size < 1: raise ValueError("chunk size less than 1") it = iter(seq) while True: chunk = list(islice(it, 0, size)) if not chunk: break yield chunk