Chris Wright wrote: > Hi, > > 1) I want to iterate over a list "N at a time" > sort of like: > > # Two at a time... won't work, obviously > > >>> for a, b in [1,2,3,4]: > ... print a,b > ... > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > TypeError: unpack non-sequence > >>> > > > Is there a nifty way to do with with list comprehensions, > or do I just have to loop over the list ? > > cheers and thanks > > chris wright
I wouldn't call this nifty, but it does use list comprehensions: (n-(len(l)%n))%n is the amount of padding (len(l)+(n-(len(l)%n))%n)/n is the number of groups (calculated by adding the padding to the length of l and then dividing by n) >>> l = range(10) >>> n = 3 >>> [(l+[None]*((n-(len(l)%n))%n))[i*n:(i+1)*n] for i in xrange((len(l)+(n-(len(l)%n))%n)/n)] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]] Regards, Todd -- http://mail.python.org/mailman/listinfo/python-list