Iterating over several lists at once

Erik Johnson ejatsomewhere.com
Wed Dec 27 14:35:10 EST 2006


"Gal Diskin" <gal.diskin at gmail.com> wrote in message
news:1167220526.849221.252410 at f1g2000cwa.googlegroups.com...
>
>
> On Dec 13, 3:47 pm, "Gal Diskin" <gal.dis... 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...

    I don't see your previous article. Not sure if you are still looking for
a solution, but here's one:

>>> [(x, y, z) for x in [1,2,3] for y in list('abc') for z in list('XY')]
[(1, 'a', 'X'), (1, 'a', 'Y'), (1, 'b', 'X'), (1, 'b', 'Y'), (1, 'c', 'X'),
(1, 'c', 'Y'), (2, 'a', 'X'), (2, 'a', 'Y'), (2, 'b', 'X'), (2, 'b', 'Y'),
(2, 'c', 'X'), (2, 'c', 'Y'), (3, 'a', 'X'), (3, 'a', 'Y'), (3, 'b', 'X'),
(3, 'b', 'Y'), (3, 'c', 'X'), (3, 'c', 'Y')]

This is a bit more compact, but I don't see anything wrong with what you
have.





More information about the Python-list mailing list