pythonloopssymmetric

How to not repeat permutations of i and j in “i not equal to j” loop in Python?


An exhaustive “i not equal to j” loop typically starts out as

for i in range(t):
    for j in range(t):
        if i is not j:

To avoid repeating symmetric results (i.e. any i with j just gives the same answer as j with i), how can we additionally skip over these permuted instances in the loop above?


Solution

  • for i in range(t):
        for j in range(i, t):
            if i != j:
    

    This guarantees that j >= i, so, therefore, there will be no i with j and j with i duplicates.

    Alternatively,

    for i in range(t):
        for j in range(i + 1, t):
    

    Will exclude i j combinations where i == j, as j > i