Intersection in Tuple Records Data in Python

PythonServer Side ProgrammingProgramming

When it is required to find the intersection of data in tuple records, a list comprehension can be used.

The list comprehension is a shorthand to iterate through the list and perform operations on it.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list. Below is a demonstration of the same −

Example

Live Demo

my_list_1 = [('Hi',1) , ('there',11), ('Will', 56)]
my_list_2 = [('Hi',1) ,('are',7) ,('you',10)]

print("The first list is : ")
print(my_list_1)
print("The second list is : ")
print(my_list_2)

my_result = [elem_1 for elem_1 in my_list_1
   for elem_2 in my_list_2 if elem_1 == elem_2]
print("The intersection of the list of tuples is : ")
print(my_result)

Output

The first list is :
[('Hi', 1), ('there', 11), ('Will', 56)]
The second list is :
[('Hi', 1), ('are', 7), ('you', 10)]
The intersection of the list of tuples is :
[('Hi', 1)]

Explanation

  • Two list of tuples are defined, and are displayed on the console.
  • Both these list of tuples are iterated over, and are checked for corresponding elements.
  • If they are equal, it is assigned to a variable.
  • Else it is ignored.
  • It is displayed on the console.
raja
Published on 12-Mar-2021 05:58:56
Advertisements