Welcome, guest | Sign In | My Account | Store | Cart

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

2 comments

Matteo Dell'Amico 12 years, 6 months ago  # | flag

One-liner using itertools:

(islice(it, i, None, parts) for i, it in enumerate(tee(iterable, parts)))

or, to generate the lists in a non-lazy way:

[list(islice(it, i, None, parts)) for i, it in enumerate(tee(iterable, parts))]
Matteo Dell'Amico 12 years, 6 months ago  # | flag

even more compact version returining a list of lists:

items = list(iterable)
return [items[i::parts] for i in range(parts)]
Created by Ian Eloff on Sat, 30 May 2009 (MIT)
Python recipes (4591)
Ian Eloff's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks