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 – Cross Pairing in Tuple List
Cross pairing in a tuple list means matching tuples from two lists based on their first element and creating pairs with their second elements. This is achieved using zip(), list comprehension, and the == operator.
What is Cross Pairing?
Cross pairing compares tuples from two lists and creates new pairs when the first elements match. For example, if both lists contain tuples starting with "Hi", their second elements get paired together.
Example
Below is a demonstration of cross pairing in tuple lists ?
list_1 = [('Hi', 'Will'), ('Jack', 'Python'), ('Bill', 'Mills'), ('goodwill', 'Jill')]
list_2 = [('Hi', 'Band'), ('Jack', 'width'), ('Bill', 'cool'), ('a', 'b')]
print("The first list is:")
print(list_1)
print("The second list is:")
print(list_2)
# Sort both lists to align matching first elements
list_1.sort()
list_2.sort()
print("The first list after sorting is:")
print(list_1)
print("The second list after sorting is:")
print(list_2)
# Cross pairing: match first elements and pair second elements
result = [(a[1], b[1]) for a, b in zip(list_1, list_2) if a[0] == b[0]]
print("The resultant list is:")
print(result)
The first list is:
[('Hi', 'Will'), ('Jack', 'Python'), ('Bill', 'Mills'), ('goodwill', 'Jill')]
The second list is:
[('Hi', 'Band'), ('Jack', 'width'), ('Bill', 'cool'), ('a', 'b')]
The first list after sorting is:
[('Bill', 'Mills'), ('Hi', 'Will'), ('Jack', 'Python'), ('goodwill', 'Jill')]
The second list after sorting is:
[('Bill', 'cool'), ('Hi', 'Band'), ('Jack', 'width'), ('a', 'b')]
The resultant list is:
[('Mills', 'cool'), ('Will', 'Band'), ('Python', 'width')]
How It Works
The cross pairing process follows these steps:
Sorting: Both lists are sorted to align tuples with matching first elements at the same positions
Zipping:
zip()pairs corresponding tuples from both listsComparison: The condition
a[0] == b[0]checks if first elements matchPairing: When first elements match, their second elements
(a[1], b[1])form a new tuple
Alternative Approach Without Sorting
You can also perform cross pairing without sorting by using nested loops ?
list_1 = [('Hi', 'Will'), ('Jack', 'Python'), ('Bill', 'Mills')]
list_2 = [('Jack', 'width'), ('Hi', 'Band'), ('Bill', 'cool')]
result = [(a[1], b[1]) for a in list_1 for b in list_2 if a[0] == b[0]]
print("Cross paired result:")
print(result)
Cross paired result:
[('Will', 'Band'), ('Python', 'width'), ('Mills', 'cool')]
Conclusion
Cross pairing in tuple lists matches tuples by their first elements and pairs their second elements. Use sorting with zip() for aligned lists, or nested comprehension for unordered matching.
