When it is required to filter tuples based on the list element that is present, list comprehension can be used.
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. The list comprehension is a shorthand to iterate through the list and perform operations on it.
Below is a demonstration of the same −
my_list = [(11, 14), (54, 56, 87), (98, 0, 10), (13, 76)] target_list = [34, 11] print("The list is : ") print(my_list) my_result = [tup for tup in my_list if any(i in tup for i in target_list)] print("The filtered tuple from the list is: ") print(my_result)
The list is : [(11, 14), (54, 56, 87), (98, 0, 10), (13, 76)] The filtered tuple from the list is: [(11, 14)]