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 – Remove rows with Numbers
When working with nested lists in Python, you may need to remove rows that contain numeric values. This can be achieved using list comprehension combined with the not, any, and isinstance functions.
Example
Below is a demonstration of removing rows containing numbers ?
data_rows = [[14, 'Pyt', 'fun'], ['Pyt', 'is', 'best'], [23, 51], ['Pyt', 'fun']]
print("The list is :")
print(data_rows)
result = [row for row in data_rows if not any(isinstance(element, int) for element in row)]
print("The result is :")
print(result)
Output
The list is : [[14, 'Pyt', 'fun'], ['Pyt', 'is', 'best'], [23, 51], ['Pyt', 'fun']] The result is : [['Pyt', 'is', 'best'], ['Pyt', 'fun']]
How It Works
The list comprehension iterates through each row in the nested list
For each row,
any()checks if any element satisfies the conditionisinstance(element, int)returnsTrueif the element is an integernot any()inverts the result, keeping rows with no integersOnly rows containing exclusively non-numeric values are retained
Alternative Method Using Filter
You can also use the filter() function for the same result ?
data_rows = [[14, 'Pyt', 'fun'], ['Pyt', 'is', 'best'], [23, 51], ['Pyt', 'fun']]
def has_no_numbers(row):
return not any(isinstance(element, int) for element in row)
result = list(filter(has_no_numbers, data_rows))
print("Filtered result:")
print(result)
Filtered result: [['Pyt', 'is', 'best'], ['Pyt', 'fun']]
Conclusion
Use list comprehension with not any(isinstance(element, int)) to remove rows containing numbers. The filter() function provides an alternative approach for better readability in complex scenarios.
