Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Make pair from two list such that elements are not same in pairs
In this article, we are going to learn how to make pairs from two lists such that no similar elements make a pair. This is useful when you need to create combinations where each pair contains different values.
Using List Comprehension
The most straightforward approach is to use nested list comprehension with a condition to filter out pairs with identical elements ?
# initializing the lists numbers_1 = [1, 2, 3, 4, 5] numbers_2 = [5, 8, 7, 1, 3, 6] # making pairs result = [(i, j) for i in numbers_1 for j in numbers_2 if i != j] # printing the result print(result)
The output of the above code is ?
[(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)]
Using itertools.product()
We can also solve this problem using the itertools.product() method, which creates the Cartesian product of the input lists. We then filter out pairs with identical elements ?
# importing the module import itertools # initializing the lists numbers_1 = [1, 2, 3, 4, 5] numbers_2 = [5, 8, 7, 1, 3, 6] # pairs pairs = itertools.product(numbers_1, numbers_2) # filtering the pairs result = [pair for pair in pairs if pair[0] != pair[1]] # printing the result print(result)
The output of the above code is ?
[(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)]
Comparison
| Method | Memory Usage | Readability | Best For |
|---|---|---|---|
| List Comprehension | Lower | High | Simple filtering conditions |
| itertools.product() | Higher | Medium | Complex Cartesian products |
Conclusion
Both methods effectively create pairs from two lists while excluding identical elements. List comprehension is more memory-efficient and readable for simple cases, while itertools.product() is better for complex Cartesian product operations.
