
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python – Cross Pairing in Tuple List
When it is required to perform cross pairing in a list of tuples, the ‘zip’ method, a list comprehension and the ‘==’ operator is used.
Example
Below is a demonstration of the same −
my_list_1 = [('Hi', 'Will'), ('Jack', 'Python'), ('Bill', 'Mills'), ('goodwill', 'Jill')] my_list_2 = [('Hi', 'Band'), ('Jack', 'width'), ('Bill', 'cool'), ('a', 'b')] print("The first list is : " ) print(my_list_1) print("The second list is :") print(my_list_2) my_list_1.sort() my_list_2.sort() print("The first list after sorting is ") print(my_list_1) print("The second list after sorting is ") print(my_list_2) my_result = [(a[1], b[1]) for a, b in zip(my_list_1, my_list_2) if a[0] == b[0]] print("The resultant list is : ") print(my_result)
Output
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')]
Explanation
Two list of tuples are defined, and displayed on the console.
Both these lists are sorted in the ascending order, and displayed on the console.
The two list of tuples are zipped and iterated over.
This is done using list comprehension.
Here, the respective elements of both the lists are compared.
If they are equal, they are stored in a list and assigned to a variable.
This is displayed as the output on the console.
- Related Articles
- Consecutive elements pairing in list in Python
- Python – Cross Pattern Pairs in List
- Flatten tuple of List to tuple in Python
- Why python returns tuple in list instead of list in list?
- Maximum element in tuple list in Python
- Python - Join tuple elements in a list
- List vs tuple vs dictionary in Python
- Difference Between List and Tuple in Python
- Grouped summation of tuple list in Python
- Modifying tuple contents with list in Python
- Python – Concatenate Rear elements in Tuple List
- Kth Column Product in Tuple List in Python
- Update each element in tuple list in Python
- Python Grouped summation of tuple list¶
- Extract digits from Tuple list Python

Advertisements