# Quick nested loop syntax?

Discussion in 'Python' started by Johannes Bauer, Nov 19, 2008.

1. ### Johannes BauerGuest

Hi group,

if I remember correctly, wasn't there a way to quickly iterate through
nested loops? Something like

a = { "a", "b", "c" }
b = { 4, 9, 13}
for (x, y) in someoperator(a, b):
print(x, y)

which would print all tuples of
"a", 4
"a", 9
"a", 13
"b", 4
"b", 9
"b", 13
"c", 4
"c", 9
"c", 13

(not nececssarily in that order, of course).

Thanks,
Johannes

--
"Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit,
verlästerung von Gott, Bibel und mir und bewusster Blasphemie."
-- Prophet und Visionär Hans Joss aka HJP in de.sci.physik
<48d8bf1d\$0\$7510\$>

Johannes Bauer, Nov 19, 2008

2. ### Mark DickinsonGuest

On Nov 19, 5:48 pm, Johannes Bauer <> wrote:
> Hi group,
>
> if I remember correctly, wasn't there a way to quickly iterate through
> nested loops? Something like

Python 2.6 has itertools.product:

http://docs.python.org/library/itertools.html#itertools.product

If you don't have Python 2.6 available, then the documentation
above also contains (almost) equivalent Python code that might
work for you.

Mark

Mark Dickinson, Nov 19, 2008

3. ### Terry ReedyGuest

Johannes Bauer wrote:
> Hi group,
>
> if I remember correctly, wasn't there a way to quickly iterate through
> nested loops? Something like
>
> a = { "a", "b", "c" }
> b = { 4, 9, 13}
> for (x, y) in someoperator(a, b):
> print(x, y)

from itertools import product
a = { "a", "b", "c" }
b = { 4, 9, 13}
for (x, y) in product(a, b):
print(x, y)

Terry Reedy, Nov 19, 2008
4. ### alex23Guest

On Nov 20, 3:48 am, Johannes Bauer <> wrote:
> a = { "a", "b", "c" }
> b = { 4, 9, 13}
> for (x, y) in someoperator(a, b):
>         print(x, y)
>
> which would print all tuples of
> "a", 4
> "a", 9
> "a", 13
> "b", 4
> "b", 9
> "b", 13
> "c", 4
> "c", 9
> "c", 13

If you're using a version of Python before 2.6, you could also use a
list comprehension:

>>> show = lambda *args: sys.stdout.write('%s\n' % args)
>>> [show((x,y)) for x in a for y in b]

('a', 4)
('a', 9)
('a', 13)
('b', 4)
('b', 9)
('b', 13)
('c', 4)
('c', 9)
('c', 13)

alex23, Nov 20, 2008