Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 all elements divisible by a specific value 'K', list comprehension along with the all() function can be used. The all() function returns True only when all elements in the tuple satisfy the divisibility condition.
Example
Let's find tuples where all elements are divisible by K ?
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)]
How It Works
The solution uses list comprehension with nested logic:
-
for sub in my_list− iterates through each tuple -
ele % K == 0 for ele in sub− checks if each element in the tuple is divisible by K -
all(...)− returns True only if all elements pass the divisibility test - Only tuples where all elements are divisible by K are included in the result
Alternative Approach Using Filter
You can also use the filter() function for the same result ?
my_list = [(45, 90, 135), (71, 92, 26), (2, 67, 98)]
K = 45
result = list(filter(lambda sub: all(ele % K == 0 for ele in sub), my_list))
print("Elements divisible by K are:", result)
Elements divisible by K are: [(45, 90, 135)]
Conclusion
Use list comprehension with all() to filter tuples where every element is divisible by K. The all() function ensures that every element in the tuple meets the divisibility condition before including the tuple in the result.
Advertisements
