Generating Unique Pairs in Python

Let’s say we’ve a list of entities, this can be anything like people names, company names, etc from which we’d like to generate unique pairs

entities = ["A", "B", "C", "D", "E"]

We can use the distinct_combinations function from more_itertools package

from more_itertools import distinct_combinations

candidate_pairs = distinct_combinations(entities, 2)

This will generate all the possible pairs with duplicates removed:

[('A', 'B'),
 ('A', 'C'),
 ('A', 'D'),
 ('A', 'E'),
 ('B', 'C'),
 ('B', 'D'),
 ('B', 'E'),
 ('C', 'D'),
 ('C', 'E'),
 ('D', 'E')]