2

Do you know how to loop over cartesian products of 100 and 200 in python, such as:

for cartesian(100,200):
 print result

1,1
1,2
.
.
.
123,197
.
.
100,200
alwbtc
  • 25,815
  • 57
  • 129
  • 182

2 Answers2

12

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,542
  • 15
  • 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
  • 74,301
  • 10
  • 131
  • 146
  • 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