In this article, we are going to learn how to make pairs from two lists such that no similar elements make a pair. Follow the below steps to solve the problem.
- Initialize the lists with elements.
- Iterate over the lists and append the pair into a list if the corresponding elements from the lists are not same.
- Print the result.
Example
Let's see the code.
# initializing the lists list_1 = [1, 2, 3, 4, 5] list_2 = [5, 8, 7, 1, 3, 6] # making pairs result = [(i, j) for i in list_1 for j in list_2 if i != j] # printing the result print(result)
If you run the above code, then you will get the following result.
Output
[(1, 5), (1, 8), (1, 7), (1, 3), (1, 6), (2, 5), (2, 8), (2, 7), (2, 1), (2, 3), (2, 6), (3, 5), (3, 8), (3, 7), (3, 1), (3, 6), (4, 5), (4, 8), (4, 7), (4, 1), (4, 3), (4, 6), (5, 8), (5, 7), (5, 1), (5, 3), (5, 6)]
We can solve the problem with itertools module as well. It provides a method called product that makes pairs of all the elements. We can filter the pairs after finding the pairs.
Example
Let's see the code.
# importing the module import itertools # initializing the lists list_1 = [1, 2, 3, 4, 5] list_2 = [5, 8, 7, 1, 3, 6] # pairs pairs = itertools.product(list_1, list_2) # filtering the pairs result = [pair for pair in pairs if pair[0] != pair[1]] # printing the result print(result)
If you run the above code, then you will get the following result.
Output
[(1, 5), (1, 8), (1, 7), (1, 3), (1, 6), (2, 5), (2, 8), (2, 7), (2, 1), (2, 3), (2, 6), (3, 5), (3, 8), (3, 7), (3, 1), (3, 6), (4, 5), (4, 8), (4, 7), (4, 1), (4, 3), (4, 6), (5, 8), (5, 7), (5, 1), (5, 3), (5, 6)]
Conclusion
If you run the above code, then you will get the following result.