When it is required to filter the tuples by the 'K'th element from a list, list comprehension and 'in' operators 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 'in' operators checks to see if the specific data is present in the iterable/data or not.
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 = [(1, 21), (25, 'abc', 'mnq'), (89, 45.65)] print("The check list has been initialized") check_list = [1, 25, 10, 21] print("The list is :") print(my_list) k=1 print("The 'k' value has been initialized to 1") my_result = [elem for elem in my_list if elem[k] in check_list] print("The filtered tuples are : ") print(my_result)
The check list has been initialized The list is : [(1, 21), (25, 'abc', 'mnq'), (89, 45.65)] The 'k' value has been initialized to 1 The filtered tuples are : [(1, 21)]