Python – Filter rows with Elements as Multiple of K

PythonServer Side ProgrammingProgramming

When it is required to filter rows with elements which are multiples of K, a list comprehension and modulus operator are used.

Example

Below is a demonstration of the same −

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 = [index for index in my_list if all(element % K == 0 for element in index)]

print("The result is :")
print(my_result)

Output

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

Explanation

  • A list of list is defined and displayed on the console.

  • The value for ‘K’ is defined and displayed on the console.

  • A list comprehension is used to iterate over the list, and modulus of each element with K is compared to 0.

  • The ‘all’ operator is used to check the output based on all elements.

  • If the value is ‘True’, this is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 10:40:16
Advertisements