Python – Cross Pairing in Tuple List

PythonServer Side ProgrammingProgramming

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.

raja
Published on 13-Sep-2021 07:19:29
Advertisements