
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter Rows with Elements as Multiple of K in Python
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.
Advertisements