Iterating over several lists at once

Gal Diskin gal.diskin at gmail.com
Wed Dec 13 08:47:07 EST 2006


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...


I was wondering if one could write this more easily in some manner
using only 1 for loop.
What I mean is something like this:

for (x1,x2,x3) in (l1,l2,l3):
    print "do something with", x1, x2, x3

Or maybe like this:

for x1 in l1, x2 in l2, x3 in l3:
    print "do something with", x1, x2, x3

However, this code obviously doesn't work...


I'd be very happy to receive ideas about how to do this in one loop and
with minimal initialization (if at all required).

Thanks in advance,
Gal




More information about the Python-list mailing list