Open In App

Python – Cross Pairing in Tuple List

Last Updated : 11 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given 2 tuples, perform cross pairing of corresponding tuples, convert to single tuple if 1st element of both tuple matches.

Input : test_list1 = [(1, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] 
Output : [(7, 3)] 
Explanation : 1 occurs as tuple element at pos. 1 in both tuple, its 2nd elements are paired and returned.

Input : test_list1 = [(10, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] 
Output : [] 
Explanation : NO pairing possible.

Method #1 : Using list comprehension

In this, we check for 1st element using conditional statements and, and construct new tuple in list comprehension.

Python3




# Python3 code to demonstrate working of
# Cross Pairing in Tuple List
# Using list comprehension
 
# initializing lists
test_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# corresponding loop in list comprehension
res = [(sub1[1], sub2[1]) for sub2 in test_list2 for sub1 in test_list1 if sub1[0] == sub2[0]]
 
# printing result
print("The mapped tuples : " + str(res))


Output

The original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]
The original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]
The mapped tuples : [(7, 3), (100, 7)]

Time complexity: O(n^2), where n is the length of the longer input list.
Auxiliary Space: O(k), where k is the length of the resulting list, since the resulting list is stored in memory.

Method #2 : Using zip() + list comprehension

In this, the task of pairing is done using zip() and conditional check is done inside list comprehension.

Python3




# Python3 code to demonstrate working of
# Cross Pairing in Tuple List
# Using zip() + list comprehension
 
# initializing lists
test_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# zip() is used for pairing
res = [(a[1], b[1]) for a, b in zip(test_list1, test_list2) if a[0] == b[0]]
 
# printing result
print("The mapped tuples : " + str(res))


Output

The original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]
The original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]
The mapped tuples : [(7, 3), (100, 7)]

Method #3 : Using Recursion

  1. Define two lists of tuples called test_list1 and test_list2.
  2. Create an empty list called result to store the cross pairs.
  3. Loop over each tuple tup1 in test_list1.
  4. For each tup1, loop over each tuple tup2 in test_list2.
  5. Compare the first elements of tup1 and tup2.
  6. If the first elements are equal, cross-pair the second elements and append the resulting tuple to the result list.
  7. After all pairs have been checked, return the result list.

Python3




def cross_pairing(test_list1, test_list2):
    result = []  # create an empty list to store the cross pairs
    for tup1 in test_list1:  # loop over each tuple in test_list1
        for tup2 in test_list2:  # loop over each tuple in test_list2
            if tup1[0] == tup2[0]:  # compare the first elements of the two tuples
                result.append((tup1[1], tup2[1]))  # if they are equal, cross pair the second elements and add to result
    return result  # return the list of cross pairs
test_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
print(cross_pairing(test_list1, test_list2))


Output

[(7, 3), (100, 7)]

Time complexity: O(n*m), where n is the length of test_list1 and m is the length of test_list2. This is because the function needs to iterate over each tuple in both lists in the worst case. The comparison of the first elements of each tuple is a constant-time operation. The appending of tuples to the result list has a time complexity of O(1) for each tuple.
Auxiliary space: O(k), where k is the size of the result list. This is because the result list is the only data structure that grows with the size of the input. The space required to store tup1, tup2, and temporary variables used in the loops is constant, regardless of the input size.

METHOD 4:Using dictionary

APPROACH:

The approach uses a dictionary to store the tuples in list 1, with the first element as the key and the second element as the value. Then, it loops through each tuple in list 2 and checks if the first element of the tuple is a key in the dictionary. If it is, a tuple is appended to the mapped tuples list with the value of the key in the dictionary as the first element and the second element of the tuple in list 2 as the second element. Finally, the list of mapped tuples is returned.

ALGORITHM:

1.Initialize an empty dictionary to store the tuples in list 1.
2.Loop through each tuple in list 1.
3.Add the tuple to the dictionary with the first element as the key and the second element as the value.
4.Initialize an empty list to store mapped tuples.
5.Loop through each tuple in list 2.
6.If the first element of the tuple in list 2 is a key in the dictionary, append a tuple of the value of the key in the dictionary and the second element of the tuple in list 2 to the mapped tuples list.
7.Return the mapped tuples list.

Python3




def cross_pairing(list1, list2):
    dict1 = {}
    for tuple1 in list1:
        dict1[tuple1[0]] = tuple1[1]
    mapped_tuples = []
    for tuple2 in list2:
        if tuple2[0] in dict1:
            mapped_tuples.append((dict1[tuple2[0]], tuple2[1]))
    return mapped_tuples
 
# Example usage
list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
mapped_tuples = cross_pairing(list1, list2)
print(mapped_tuples)


Output

[(7, 3), (100, 7)]

Time complexity: O(n)
Auxiliary Space: O(n)



Similar Reads

Python | Consecutive elements pairing in list
Sometimes, while working with lists, we need to pair up the like elements in the list and then store them as lists of lists. This particular task has its utility in many domains, be it web development or day-day programming. Let's discuss certain ways in which this can be achieved. Method #1: Using list comprehension The list comprehension can be e
5 min read
Python - K difference index pairing in list
Sometimes while programming, we can face a problem in which we need to perform K difference element concatenation. This problem can occur at times of school programming or competitive programming. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + zip() Combination of above functionalities can be
5 min read
Python | Tuple list cross multiplication
Sometimes, while working with Python records, we can have a problem in which we need to perform cross multiplication of list of tuples. This kind of application is popular in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip() The combination of the above functionaliti
5 min read
Python - Successive element pairing
Sometimes, while working with Python list, we can have a problem in which we need to construct tuples, with the succeeding element, whenever that element matches a particular condition. This can have potential application in day-day programming. Let’s discuss a way in which this task can be performed. Method : Using zip() + list comprehension This
4 min read
Python - Consecutive Triple element pairing
Sometimes, while working with lists, we need to triple pair up the like elements in list and then store them as lists of list. This particular task has it’s utility in many domains, be it web development or day-day programming. Let’s discuss certain ways in which this can be achieved. Method #1 : Using list comprehension The list comprehension can
4 min read
Python | Custom Consecutive Character Pairing
Sometimes, while working with Python Strings, we can have problem in which we need to perform the pairing of consecutive strings with deliminator. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using join() + list comprehension The combination of above functions can be used to p
4 min read
Python - Sorted order Dictionary items pairing
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform reordering of dictionary items, to pair key and values in sorted order, smallest pairing to smallest value, largest to largest value and so on. This kind of application can occur in competitive domain and day-day programming. Lets discuss certain ways
3 min read
Python - Minimum value pairing for dictionary keys
Given two lists, key and value, construct a dictionary, which chooses minimum values in case of similar key value pairing. Input : test_list1 = [4, 7, 4, 8], test_list2 = [5, 7, 2, 9] Output : {8: 9, 7: 7, 4: 2} Explanation : For 4, there are 2 options, 5 and 2, 2 being smallest is paired. Input : test_list1 = [4, 4, 4, 4], test_list2 = [3, 7, 2, 1
7 min read
Python - Cross tuple summation grouping
Sometimes, while working with Python tuple records, we can have a problem in which we need to perform summation grouping of 1st element of tuple pair w.r.t similar 2nd element of tuple. This kind of problem can have application in day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list = [(1, 5), (7, 4
7 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
three90RightbarBannerImg