Python program to find tuples which have all elements divisible by K from a list of tuples


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 −

Example

 Live Demo

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))

Output

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)]

Explanation

  • 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.

Updated on: 15-Apr-2021

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements