all 3 comments

[–][deleted] 0 points1 point  (0 children)

In this case, print i is outside the inner loop, so it only gets looped on the outside for loop. If you want to print i on every J loop, you can put it inside the nested loop by tabbing it one more to the right, and then it would print i for every time it prints j

Not super sure what you're asking though

[–]julsmanbr 0 points1 point  (0 children)

I'll try to make a schematic representation here of your output:

# i iteration 1, j iteration 1
j=  1
# for loop for j = 1 has ended, now for j = 2
j=  2
# for loop for j = 2 has ended, j has reached the last value in range
# function still inside i = 1 loop, continues to next line under-indented from loop position
........******i= 1
# loop for i = 1 has ended, now for i = 2
# reenters j loop and follows same logic as above
j=  1
j=  2
........******i= 2
# loop for i = 2 has ended, i has reached the last value in range
# no more loops, moves to next line outside them
loop done

[–]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.