Quick nested loop syntax?

J

Johannes Bauer

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
 
T

Terry Reedy

Johannes said:
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)
 
A

alex23

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top