2

Do you know how to loop over cartesian products of two ranges in python, such as:

for i,j in cartesian(100,200):
 print i, j

0,0
0,1
.
.
.
123,197
.
.
99,199
nadapez
  • 2,603
  • 2
  • 20
  • 26
alwbtc
  • 28,057
  • 62
  • 134
  • 188

2 Answers2

13

The product function will work:

from itertools import product
for j in product(range(100), range(200)):
  print j

Alternatively, from the product documentation:

Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

colcarroll
  • 3,632
  • 17
  • 25
4

Maybe I'm missing something, but isn't it as simple as this:

for i in range(100):
    for j in range(200):
        print i, j

Slightly more optimized version:

inner_range = range(200)
for i in range(100):
    for j in inner_range:
        print i, j
Wolph
  • 78,177
  • 11
  • 137
  • 148
  • which is faster, yours or JLLagrange's? – alwbtc Sep 12 '13 at 12:52
  • Most likely this version since it's the simplest most pure Python solution you can get. Using the product method gives you an extra wrapper so inherently a bit of speed loss but it might omit generating the second range a hundred times. Having that said, any difference is bound to be negligible anyhow. – Wolph Sep 12 '13 at 13:22
  • Why didn't you use `outer_range = range(100)`? – alwbtc Sep 12 '13 at 18:55
  • 1
    The outer range is only used once, the inner range 100 times since it's within the for loop. For cleanless you could but it shouldn't make any difference. – Wolph Sep 12 '13 at 21:46
  • product seems to be a lot faster when iterating over data like numpy arrays. – Hyperplane Feb 15 '19 at 15:45