Iterating over several lists at once

Kay Schluehr kay.schluehr at gmx.net
Wed Dec 13 09:54:13 EST 2006


Gal Diskin schrieb:

> Hi,
> I am writing a code that needs to iterate over 3 lists at the same
> time, i.e something like this:
>
> for x1 in l1:
>     for x2 in l2:
>         for x3 in l3:
>             print "do something with", x1, x2, x3
>
> What I need to do is go over all n-tuples where the first argument is
> from the first list, the second from the second list, and so on...

Heard about recursion?

def collect(L,*lists):
    if not lists:
        return [(x,) for x in L]
    collection = []
    for x in L:
        for y in collect(lists[0],*lists[1:]):
            collection.append((x,)+y)
    return collection

for item in collect( l1, l2, l3):
    func(*item)

Here is the same in generator form

def collect(L,*lists):
    if not lists:
        for x in L:
            yield (x,)
    else:
        for x in L:
            for y in collect(lists[0],*lists[1:]):
                yield (x,)+y

( o.k - it required two nested for-loops in each implementation :)




More information about the Python-list mailing list