0

I have a list of tuples in python.

list = [(1,2), (1,3), (1,4), (2,3), (2, 4), (3,4)]

How can i print all of the possible pairs of tuples? I want to avoid duplication. For example (1,2), (2,3) and (2,3), (1,2) are duplicated.

The expected result is:

(1,2), (1,3)
(1,2), (1,4)
(1,2), (2,3)
(1,2), (2,4)
(1,2), (3,4)
(1,3), (1,4)
(1,3), (2,3)
(1,3), (2,4)
(1,3), (3,4)
(1,4), (2,3)
(1,4), (2,4)
(1,4), (3,4)
(2,3), (2,4)
(2,3), (3,4)
(2,4), (3,4)
Supertwister
  • 105
  • 1
  • 1
  • 8

2 Answers2

1

Try this code:

from itertools import combinations 

# Get all combinations and length 2 
comb = combinations([(1,2), (1,3), (1,4), (2,3), (2, 4), (3,4)], 2) 

# Print the obtained combinations 
for i in list(comb): 
    print(i[0],",", i[1])

Output:

(1, 2) , (1, 3)
(1, 2) , (1, 4)
(1, 2) , (2, 3)
(1, 2) , (2, 4)
(1, 2) , (3, 4)
(1, 3) , (1, 4)
(1, 3) , (2, 3)
(1, 3) , (2, 4)
(1, 3) , (3, 4)
(1, 4) , (2, 3)
(1, 4) , (2, 4)
(1, 4) , (3, 4)
(2, 3) , (2, 4)
(2, 3) , (3, 4)
(2, 4) , (3, 4)
Shadab Hussain
  • 794
  • 6
  • 24
1

Take a look at combinations in itertools.

>>> l = [(1,2), (1,3), (1,4), (2,3), (2, 4), (3,4)]
>>> import itertools
>>> combinations = itertools.combinations(l, 2)
>>> for combination in combinations:
...   print(combination)
...
((1, 2), (1, 3))
((1, 2), (1, 4))
((1, 2), (2, 3))
((1, 2), (2, 4))
((1, 2), (3, 4))
((1, 3), (1, 4))
((1, 3), (2, 3))
((1, 3), (2, 4))
((1, 3), (3, 4))
((1, 4), (2, 3))
((1, 4), (2, 4))
((1, 4), (3, 4))
((2, 3), (2, 4))
((2, 3), (3, 4))
((2, 4), (3, 4))
Querenker
  • 2,242
  • 1
  • 18
  • 29