This could also be easily modified to return n iterators, but was outside of my needs. Handy for splitting up the workload for use with multiple threads/processes.
Python, 13 lines
1 2 3 4 5 6 7 8 9 10 11 12 13
def divide(iterable, parts): ''' Partitions an iterable into parts number of lists. ''' items = list(iterable) seqs = [ for _ in xrange(parts)] while items: for i in xrange(parts): if not items: break seqs[i].append(items.pop()) return seqs
One-liner using itertools:
or, to generate the lists in a non-lazy way:
even more compact version returining a list of lists: