Nested loop through list avoiding same element

Viewed 71

I can't explain the concept well at all, but I am trying to loop through a list using a nested loop, and I can't figure out how to avoid them using the same element.

list = [1, 2, 2, 4]
for i in list:
    for j in list:
        print(i, j) # But only if they are not the same element

So the output should be:

1 2
1 2
1 4
2 1
2 2
2 4
2 1
2 2
2 4
4 1
4 2
4 2

Edit as the solutions don't work in all scenarios:

The if i != j solution only works if all elements in the list are different, I clearly chose a poor example, but I meant same element rather than the same number; I have changed the example

2 Answers

You can compare the indices of the two iterations instead:

lst = [1, 2, 2, 4]
for i, a in enumerate(lst):
    for j, b in enumerate(lst):
        if i != j:
            print(a, b)

You can also consider using itertools.permutations for your purpose:

lst = [1, 2, 2, 4]
from itertools import permutations
for i, j in permutations(lst, 2):
    print(i, j)

Both would output:

1 2
1 2
1 4
2 1
2 2
2 4
2 1
2 2
2 4
4 1
4 2
4 2
Related