0

I am looking for an iterator which takes as an input multiple ranges in python (or for example lists) and returns all possible combinations for these. Preferably in an iterator so it does not store all combinations in memory. I know how to code it myself, but it seems to me a quite common function so i cannot imagine that it doesn't exists already in some library. This is basically the idea:

a = range(0,2)
b = range(2,4)

for i,j in someFunc(a,b):
    print(i,j)

This would then print:

0 2
0 3
1 2
1 3

This can ofcourse be achieved by multiple loops:

for i in a:
    for j in b:
        print(i,j)

But i am looking for one function which can accept unlimited ranges as arguments. It seems as such a common function, but i have not been able to find it anywhere.

user3053216
  • 777
  • 1
  • 9
  • 24

2 Answers2

1

You want itertools.product():

>>> from itertools import product
>>> list(product(range(0, 2), range(2, 4)))
[(0, 2), (0, 3), (1, 2), (1, 3)]
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
1

itertools.product does a catesian product:

>>> from itertools import product
>>> A = [1, 2 , 3 ]
>>> B = [3, 5, 4 ]
>>> product(A,B) 
<itertools.product object at 0x7f4428d75e10>
>>> for i in product(A,B): 
...     print i 
... 
(1, 3)
(1, 5)
(1, 4)
(2, 3)
(2, 5)
(2, 4)
(3, 3)
(3, 5)
(3, 4)
>>> 
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117