Iterating over several lists at once

Maksim Kasimov maksim.kasimov at gmail.com
Wed Dec 13 11:49:27 EST 2006


Hi,

if you "needs to iterate over 3 lists at the same" and according your example

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


i has guessed that you need this (may be i was wrong):


a = (1,2,3, 1)
b = (4,5,6)
c = (7,8,9, 2, 3)

for x, y, z in zip(a, b, c):
     print x, y, z


or this


for x, y, z in map(None, a, b, c):
     print x,y,z


Try both examples with tuples that have various length, they have difference






Gal Diskin wrote:
> 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
> 


-- 
Maksim Kasimov



More information about the Python-list mailing list