Quick nested loop syntax?

alex23 wuwei23 at gmail.com
Wed Nov 19 21:40:03 EST 2008


On Nov 20, 3:48 am, Johannes Bauer <dfnsonfsdu... at gmx.de> 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)



More information about the Python-list mailing list