1
a = [5,7,3,1,2]
for i in a:
    for j in a:
        if(i==j):
            continue
        else:
            print(i,j)
    print("")

output:

5 7
5 3
5 1
5 2

7 5
7 3
7 1
7 2

3 5
3 7
3 1
3 2

1 5
1 7
1 3
1 2

2 5
2 7
2 3
2 1

My code just displays all the values but will skip the values which matches but if I want dont want to display values which are printed already like if value (5,7) is printed it should not print again as (7,5). Once value 5 7 is printed so for next iteration it should not display 7 5 and this should happen with all values in array. Please someone help me. Thank you. If there is duplication of question please guide me to that question.

Shivam
  • 155
  • 1
  • 9
  • Could you please add expected output as well? – Chris Aby Antony Aug 31 '18 at 07:10
  • Possible duplicate of [The pythonic way to generate pairs](https://stackoverflow.com/questions/6499327/the-pythonic-way-to-generate-pairs) – Ankur Sinha Aug 31 '18 at 07:12
  • Possible duplicate of [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – Sayse Aug 31 '18 at 07:13
  • No it is not duplicate my question is different from others please read it carefully – Shivam Sep 03 '18 at 09:19

3 Answers3

7

Easiest is to use itertools.combinations which takes care of avoiding repetitions for you:

from itertools import combinations
a = [5, 7, 3, 1, 2]
for x, y in combinations(a, 2):
    print(x, y)

5 7
5 3
5 1
5 2
7 3
7 1
7 2
3 1
3 2
1 2

If you want to do it without library help, you can do the following, using enumerate and slicing:

for i, x in enumerate(a):
    for y in a[i+1:]:  # combine only with elements after x (index i)
        print(x, y)
user2390182
  • 72,016
  • 6
  • 67
  • 89
2

Use combinations form itertools:

from itertools import combinations
for tup in combinations([5,7,3,1,2],2):
    print(tup[0],tup[1])
5 7
5 3
5 1
5 2
7 3
7 1
7 2
3 1
3 2
1 2
Space Impact
  • 13,085
  • 23
  • 48
0

Yes you can. Try following:

a = [5,7,3,1,2]
for i in range(len(a)):
    for j in a[i:]:
        if(a[i]==j):
            continue
        else:
            print(a[i],j)
    print("")

This will give output:

5 7
5 3
5 1
5 2

7 3
7 1
7 2

3 1
3 2

1 2
Sumedh Junghare
  • 381
  • 2
  • 4
  • 21