Iterating over several lists at once

Gal Diskin gal.diskin at gmail.com
Wed Dec 13 09:51:53 EST 2006


Nothing seriously wrong, but it's not too elegent. Especially when the
number of lists you want to iterate over gets bigger (especially
because of the indentation in python). As you noticed (an phrased
better than me), what I was wondering is if there is a way to iterate
over the cartesian product, but without actually doing all n for loops
but using a single "for" loop.

Thanks for replying me.


On Dec 13, 3:58 pm, Roberto Bonvallet <Roberto.Bonval... at cern.ch>
wrote:
> 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, x3What's wrong with this?
>
> [...]
>
> > I'd be very happy to receive ideas about how to do this in one loop and
> > with minimal initialization (if at all required).def cartesian_product(l1, l2, l3):
>     for i in l1:
>         for j in l2:
>             for k in l3:
>                 yield (i, j, k)
>
> for (i, j, k) in cartesian_product(l1, l2, l3):
>     print "do something with", i, j, k
> 
> --
> Roberto Bonvallet




More information about the Python-list mailing list