Python – Filter rows with only Alphabets from List of Lists

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

When it is required to filter the rows that contains only alphabets in a list of lists, the list is iterated over and the ‘isalpha’ method is used to check if an alphabet is present or not.

Example

Below is a demonstration of the same

my_list = [["python", "is", "best"], ["abc123", "good"],["abc def ghij"], ["abc2", "gpqr"]]

print("The list is :")
print(my_list)
my_result = [sub for sub in my_list if all(element.isalpha() for element in sub)]

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

Output

The list is :
[['python', 'is', 'best'], ['abc123', 'good'], ['abc def ghij'], ['abc2', 'gpqr']]
The result is :
[['python', 'is', 'best']]

Explanation

• A list of list elements is defined that contains string values.

• This is displayed on the console.

• The elements are iterated over and checked to see if they are alphabets.

• This is done using the ‘isalpha’ method.

• The results are assigned to a variable.

• This variable is displayed as output on the console.

Updated on 20-Sep-2021 06:45:59