Python - Unique Pairs in List


Python is a very commonly used programming language used for many different purposes by programmer all over the world for different purposes. The various filed of application of python are web development, machine learning, data science and to perform many different processes with automation. Python stores its data in different data sets such as list, dictionary sets etc. A similar process that every programmer must go through while working on list is to find unique pair in the list. In this article we are going to learn about different methods that can be used to find unique pairs in a list of data.

Different Methods to Find Unique Pairs in List

Nested Loops

This is a very simple method of finding unique pairs in list using the nested loops method. Nested loops mean a situation in which one loop exists inside another loop. Let’s take an example to understand it in a better manner:

Example

def checking_of_uniqueness(list): # The input of the list is given to a function checking_of_uniqueness
    new_list = [] # A new list is created which will contain all the unique pairs
    for i in range(len(list)): # In this loop each element in the list is checked
        for j in range(i + 1, len(list)): # In this loop all remaining elements are checked after current index
            unique_pair = (list[i], list[j]) # A tuple is created to store all the unique pairs in one variable (unique_pair)
            new_list.append(unique_pair)
    return new_list

# Example 
names = ['Jack', 'Sam', 'John', 'Daniel'] # The input of list is given
final_pairs = checking_of_uniqueness(names) # The function checking_of_uniqueness is run
print(final_pairs) #The final output of different pairs is displayed

Output

The output of the above example will be as follows:

[('Jack', 'Sam'), ('Jack', 'John'), ('Jack', 'Daniel'), ('Sam', 'John'), ('Sam', 'Daniel'), ('John', 'Daniel')] 

Itertools

We can use the functions of itertools to find different unique pairs present in a list. The itertool library is used for checking each element present in the list efficiently. Let’s take an example to understand this method in a better way:

Example

from itertools import combinations # Do not forget to import itertools or else error might occur

def checking_of_uniqueness(lists): # The input of the list is given to a function checking_of_uniqueness
    return list(combinations(lists, 2)) #The combinations function of itertools is used to find unique pairs in the list

# Example 
names = ['Jack', 'Sam', 'John', 'Daniel'] # The input of list is given
final_pairs = checking_of_uniqueness(names) # The function checking_of_uniqueness is run
print(final_pairs) #The final output of different pairs is displayed

Output

The input of the above example will be as follows:

[('Jack', 'Sam'), ('Jack', 'John'), ('Jack', 'Daniel'), ('Sam', 'John'), ('Sam', 'Daniel'), ('John', 'Daniel')]

List Comprehension

List Comprehension is used to generate shorter syntax for creating a new list. We will use list comprehension to create a new list of unique pairs. Let’s take an example to understand it in a better way:

Example

def checking_of_uniqueness(list): # The input of the list is given to a function checking_of_uniqueness
    return [(list[i], list[j]) for i in range(len(list)) for j in range(i + 1, len(list))]  # We create two different nested loops in a single line of code with the help of list comprehension method to find the uniqueness using tuple 

# Example 
names = ['Jack', 'Sam', 'John', 'Daniel'] # The input of list is given
final_pairs = checking_of_uniqueness(names) # The function checking_of_uniqueness is run
print(final_pairs) #The final output of different pairs is displayed

Output

The output of the above example will be as follows:

('Jack', 'Sam'), ('Jack', 'John'), ('Jack', 'Daniel'), ('Sam', 'John'), ('Sam', 'Daniel'), ('John', 'Daniel')] 

Sets

In this method we will convert the list into sets and then we will remove the supplicate elements and find the unique pairs in the data provided. Let’s take an example to understand it in a better way:

Example

def checking_of_uniqueness(lst):# The input of the list is given to a function checking_of_uniqueness
    unique_elements = set(lst) # We convert the list into sets which remove all the same elements in the list
    unique_pairs = []
    for i in unique_elements:
        for j in unique_elements:
            if i < j:  # Ensure that the pairs are unique and ordered
                unique_pairs.append((i, j))
    return unique_pairs

# Example 
names = ['Jack', 'Sam', 'John', 'Daniel'] # The input of list is given
final_pairs = checking_of_uniqueness(names) # The function checking_of_uniqueness is run
print(final_pairs) #The final output of different pairs is displayed

Output

The output of the above example will look as follows:

[('Jack', 'Sam'), ('Jack', 'John'), ('Daniel', 'Jack'), ('Daniel', 'Sam'), ('Daniel', 'John'), ('John', 'Sam')])]

Recursive Backtracking

This is a complex method of finding unique pairs from a list but this method is very efficient in compare to the above suggested method. It is suggested to use this method in case of lists having large amount of data in it. It forms pair by checking all the different elements in it one by one. Let’s take an example to understand it in a better way:

Example

def checking_of_uniqueness(lists):# The input of the list is given to a function checking_of_uniqueness def backtrack(start, path):   
    def backtrack(start, path):
        if len(path) == 2: # Path is a temporary list to store the pairs as they are being built
            unique_pairs.append(tuple(path)) # Once the pair is completed, it is moved into the unique_pairs
        else:
            for i in range(start, len(lists)): #If the pair remains incomplete the function calls itself and increments the function `start` and then updates itself according to it
                if lists[i] not in path:  
                    path.append(lists[i])
                    backtrack(i + 1, path)
                    path.pop() #This function removes the last element from the list

    unique_pairs = []
    backtrack(0, [])
    return unique_pairs

# Example 
names = ['Jack', 'Sam', 'John', 'Daniel'] # The input of list is given
final_pairs = checking_of_uniqueness(names) # The function checking_of_uniqueness is run
print(final_pairs) #The final output of different pairs is displayed

Output

The output of the above example will be as follows:

[('Jack', 'Sam'), ('Jack', 'John'), ('Jack', 'Daniel'), ('Sam', 'John'), ('Sam', 'Daniel'), ('John', 'Daniel')] 

Conclusion

It is very important to have knowledge about different methods to find unique pairs in list to become an efficient programmer. This article gives different method that can be used to find unique pairs from a list.

Updated on: 01-Aug-2023

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements