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 program to omit K length Rows
When working with lists of lists, you may need to filter out rows based on their length. This Python program demonstrates how to omit rows that have exactly K elements using iteration and the len() method.
Example
Below is a demonstration of the same −
my_list = [[41, 7], [8, 10, 12, 8], [10, 11], [6, 82, 10]]
print("The list is :")
print(my_list)
my_k = 2
print("The value of K is")
print(my_k)
my_result = []
for row in my_list:
if len(row) != my_k :
my_result.append(row)
print("The resultant list is :")
print(my_result)
Output
The list is : [[41, 7], [8, 10, 12, 8], [10, 11], [6, 82, 10]] The value of K is 2 The resultant list is : [[8, 10, 12, 8], [6, 82, 10]]
How It Works
A list of lists is defined and displayed on the console.
The K value is defined and displayed on the console.
An empty list is created to store the result.
The original list is iterated over row by row.
If the length of the current row is not equal to K, it is appended to the result list.
The filtered result is displayed on the console.
Using List Comprehension
You can achieve the same result more concisely using list comprehension −
my_list = [[41, 7], [8, 10, 12, 8], [10, 11], [6, 82, 10]]
my_k = 2
# Filter out rows with length K
my_result = [row for row in my_list if len(row) != my_k]
print("Original list:", my_list)
print("K value:", my_k)
print("Filtered list:", my_result)
Original list: [[41, 7], [8, 10, 12, 8], [10, 11], [6, 82, 10]] K value: 2 Filtered list: [[8, 10, 12, 8], [6, 82, 10]]
Conclusion
Use iteration with len() and append() for readable filtering. List comprehension provides a more concise approach for the same operation.
