Quick nested loop syntax?

Vlastimil Brom vlastimil.brom at gmail.com
Wed Nov 19 19:24:17 CET 2008


2008/11/19 Johannes Bauer <dfnsonfsduifb at gmx.de>

> 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
>
> --
>
If you are running the code in python 3, as suggested by the use of the set
literals, the mentioned itertools.product() is probably the straightforward
way.
Another possibility could be a nested generator expression (here using lists
- preserving the order):
>>> a = ["a", "b", "c"]
>>> b = [4, 9, 13]
>>> for item in ((ax, bx) for ax in a for bx in b): print item
...
('a', 4)
('a', 9)
('a', 13)
('b', 4)
('b', 9)
('b', 13)
('c', 4)
('c', 9)
('c', 13)
>>>
regards
   vbr
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081119/d05789b1/attachment.html>


More information about the Python-list mailing list