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
Python – Filter rows with Elements as Multiple of K
When working with nested lists in Python, you might need to filter rows where all elements are multiples of a specific value K. This can be achieved using list comprehension combined with the all() function and modulus operator.
Syntax
The general syntax for filtering rows with elements as multiples of K is ?
result = [row for row in nested_list if all(element % K == 0 for element in row)]
Example
Below is a demonstration of filtering rows where all elements are multiples of K ?
my_list = [[15, 10, 25], [14, 28, 23], [120, 55], [55, 30, 203]]
print("The list is:")
print(my_list)
K = 5
print("The value of K is:")
print(K)
my_result = [row for row in my_list if all(element % K == 0 for element in row)]
print("The result is:")
print(my_result)
The list is: [[15, 10, 25], [14, 28, 23], [120, 55], [55, 30, 203]] The value of K is: 5 The result is: [[15, 10, 25], [120, 55]]
How It Works
The solution works through the following steps ?
The list comprehension iterates through each row in the nested list
For each row,
all(element % K == 0 for element in row)checks if every element is divisible by KThe modulus operator
%returns 0 when a number is perfectly divisibleThe
all()function returnsTrueonly if all elements satisfy the conditionOnly rows where all elements are multiples of K are included in the result
Example with Different K Values
Let's see how the same data behaves with different K values ?
data = [[12, 18, 24], [10, 15, 25], [6, 9, 12]]
# Filter with K = 3
result_k3 = [row for row in data if all(element % 3 == 0 for element in row)]
print("Multiples of 3:", result_k3)
# Filter with K = 6
result_k6 = [row for row in data if all(element % 6 == 0 for element in row)]
print("Multiples of 6:", result_k6)
Multiples of 3: [[12, 18, 24], [6, 9, 12]] Multiples of 6: [[12, 18, 24], [6, 9, 12]]
Conclusion
List comprehension with all() and modulus operator provides an efficient way to filter rows based on divisibility conditions. This approach is both readable and performs well for moderate-sized datasets.
