When it is required to filter tuples product greater than K, a list comprehension is used.
Example
Below is a demonstration of the same −
def tuples_product(index): my_result = 1 for element in index: my_result *= element return my_result my_list = [(14, 25, 17), (2, 3, 5), (81, 42, 21), (6, 2, 1)] print("The list is :") print(my_list) K = 15 print("The value of K is :") print(K) my_result = [index for index in my_list if tuples_product(index) > K] print("The result is :") print(my_result)
Output
The list is : [(14, 25, 17), (2, 3, 5), (81, 42, 21), (6, 2, 1)] The value of K is : 15 The result is : [(14, 25, 17), (2, 3, 5), (81, 42, 21)]
Explanation
A method named ‘tuples_product’ is defined that takes tuple as a parameter and returns the product of every element in the tuple as output.
Outside the method, a list is defined and displayed on the console.
The value for key is defined and is displayed on the console.
A list comprehension is used to iterate over the list, and for every element, the method is called.
The method’s result is compared to K.
If it is greater than K, it is added to a list and is assigned to a variable.
This is the output that is displayed on the console.