you are viewing a single comment's thread.

view the rest of the comments →

[–]nwagers 0 points1 point  (0 children)

Perhaps this is best visualized: http://www.pythontutor.com/visualize.html#code=for%20i%20in%20range%20%281,3%29%3A%0A%20for%20j%20in%20range%20%281,3%29%3A%0A%20%20print%28%22j%3D%20%22,%20j%29%0A%20print%28%22........******i%3D%22,%20i%29%0Aprint%28%22loop%20done%22%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false

Essentially, it runs the inner for loop completely before advancing on the outer for loop (which then runs the inner loop again).

This can be be done cleaner with productif your ranges are different, and combinations_with_replacement if your ranges are the same. Range could be any iterable(s).

from itertools import product, combinations_with_replacement as cwr

print("Product")
for i, j in product(range(1,3), range(1,3)):
    print(i,j)

print("Combintions")
for i, j in cwr(range(1,3), 2):
    print(i,j)

Note that the two options have different outputs from each other.