18

Consider if I had a function that took a tuple argument (x,y), where x was in the range(X), and y in the range(Y), the normal way of doing it would be:

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

is there a way to do

for xy in something_like_range(X,Y):
    function(xy)

such that xy was a tuple (x,y)?

Bolster
  • 7,460
  • 13
  • 61
  • 96

5 Answers5

19

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)
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
5

You can use itertools.product():

from itertools import product
for xy in product(range(X), range(Y)):
    function(xy)
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • don't need a comma b/w x and y? – yishairasowsky Oct 20 '21 at 12:49
  • @yishairasowsky The code works as written. `xy` will be a pair (tuple with two elements) containing one value from `X` and one from `Y` in each iteration. You can unpack the tuple by using `x, y` as the loop variable if you want to. I used `xy` as a single value here because this is what the OP asked for. – Sven Marnach Oct 20 '21 at 15:09
4

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 0
0 1
1 0
1 1
N 1.1
  • 12,418
  • 6
  • 43
  • 61
2

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

from itertools import product

for x, y in product(range(X), range(Y)):
    function(x, y)
gruszczy
  • 40,948
  • 31
  • 128
  • 181
0
from itertools import product

def something_like_range(*sizes):
    return product(*[range(size) for size in sizes])

for a usage close to what you wanted:

for x,y in something_like_range(X,Y):
    your_function(x,y)

=)

rakslice
  • 8,742
  • 4
  • 53
  • 57