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 condition

  • isinstance(element, int) returns True if the element is an integer

  • not any() inverts the result, keeping rows with no integers

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

Updated on: 2026-03-26T01:20:44+05:30

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements