5

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

4
  • I disagree, I said explicitly asked about them being the same element rather than just the same number, how else would you have worded it? Commented Mar 16, 2020 at 14:19
  • 1
    @JonathanDyke What if your list is [2, 2, 2]. What is the expected output? Commented Mar 16, 2020 at 14:22
  • 2
    @JonathanDyke I didnot see that you changed the original list too. ;) I apologize. Commented Mar 16, 2020 at 14:23
  • @a_guest regardless of the numbers it would be all permutations of list[i] list[j] except where i == j, so in the case of [2, 2, 2] it would be 2 2 six times Commented Mar 16, 2020 at 14:24

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

3

Simply:

if i != j:
    print(i, j)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.