Python – Remove rows with Numbers

PythonServer Side ProgrammingProgramming

When it is required to remove rows with numbers, a list comprehension and the ‘not’ and ‘any’ operators are used.

Example

Below is a demonstration of the same −

my_list = [[14, 'Pyt', 'fun'], ['Pyt', 'is', 'best'], [23, 51], ['Pyt', 'fun']]

print("The list is :")
print(my_list)

my_result = [index for index in my_list if not any(isinstance(element, int) for element in index)]

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

Output

The list is :
[[14, 'Pyt', 'fun'], ['Pyt', 'is', 'best'], [23, 51], ['Pyt', 'fun']]
The result is :
[['Pyt', 'is', 'best'], ['Pyt', 'fun']]

Explanation

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

  • A list comprehension is used to iterate over the list, and each element is checked for belonging to integer type.

  • The element type is checked using ‘isinstance’ method.

  • If it is an integer, it is removed.

  • Otherwise, it is stored in a list, and assigned to a variable.

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

raja
Published on 08-Sep-2021 09:05:17
Advertisements