Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets [].
Example:
list = [3 ,1, 5, 7]
We have two lists with each element a tuple and we need to perform cross pairing i.e. we need to create a tuple with second elements of tuples whose first elements are the same.
Here is an example for a better understanding of the problem,
Input:
tupList1 = [(1, 8), (9, 6), (0, 8), (4,5)]
tupList2 = [(7, 8), (2, 5), (3, 6), (4,7)]
Output:
(5, 7)
Explanation: Here, only the tuples (4,5) and (4,7) have common first elements. So, cross pairing will consider both of them only.
To solve this problem, we will be traversing the list and then checking for each tuple if there exists a tuple in another list that has the same first elements as this tuple. If yes, we will make a tuple with the second values of both the tuples and store them in a list.
For performing this task in the python programming language, we have more than one way as python has many built-in methods to reduce our efforts in tasks.
Method 1:
One way to solve the problem is by using list comprehension along with comparison using condition statements to create a new tuple that will have a second element of the tuple whose first element is the same.
Output:
Method 2:
An alternate method to solve the problem is by using the zip() method with the condition of the first element's equality along with list comprehension.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer