When it is required to find tuples that have elements that are divisible by a specific element ‘K’, the list comprehension can be used.
Below is a demonstration of the same −
my_list = [(45, 90, 135), (71, 92, 26), (2, 67, 98)] print("The list is : ") print(my_list) K = 45 print("The value of K has been initialized to ") print(K) my_result = [sub for sub in my_list if all(ele % K == 0 for ele in sub)] print("Elements divisible by K are : " + str(my_result))
The list is : [(45, 90, 135), (71, 92, 26), (2, 67, 98)] The value of K has been initialized to 45 Elements divisible by K are: [(45, 90, 135)]
A list of tuple is defined, and is displayed on the console.
The value of K is defined, and is displayed on the console.
The list comprehension is used to iterate through the elements.
Every element in the list of tuple is checked to see if it is divisible by K.
If it is divisible by K, it is converted to a list element, and stored in a variable.
This is displayed as output on the console.