Pythonic shortcut for doubly nested for loops? Pythonic shortcut for doubly nested for loops? python python

Pythonic shortcut for doubly nested for loops?


You can use product from itertools

>>> from itertools import product>>> >>> for x,y in product(range(3), range(4)):...   print (x,y)... (0, 0)(0, 1)(0, 2)(0, 3)(1, 0)(1, 1)(1, 2)(1, 3)... and so on

Your code would look like:

for x,y in product(range(X), range(Y)):    function(x,y)


You can use itertools.product():

from itertools import productfor xy in product(range(X), range(Y)):    function(xy)


Pythonic they are -> (modify according to your requirements)

>>> [ (x,y)   for x in range(2)   for y in range(2)][(0, 0), (0, 1), (1, 0), (1, 1)]

Generator version :

gen = ( (x,y)   for x in range(2)   for y in range(2) )>>> for x,y in gen:...     print x,y... 0 00 11 01 1