Iterating over several lists at once

Roy Smith roy at panix.com
Wed Dec 27 14:45:40 EST 2006


In article <1166017627.699257.166740 at 16g2000cwy.googlegroups.com>,
 "Gal Diskin" <gal.diskin at gmail.com> 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...

Take a look at 
http://mail.python.org/pipermail/python-list/2001-September/104983.html

or

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159975

There's nothing magic about either -- fundamentally, you're still doing an 
N^3 operation and it's going to be slow.  You might want to stop and think 
if there's some better algorithm than an exhaustive search of the entire 
domain space for whatever it is that you're trying to do.



More information about the Python-list mailing list