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 K

  • The modulus operator % returns 0 when a number is perfectly divisible

  • The all() function returns True only if all elements satisfy the condition

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

Updated on: 2026-03-26T01:25:16+05:30

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements