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 – Filter rows with only Alphabets from List of Lists
When working with a list of lists containing strings, you may need to filter rows that contain only alphabetic characters. Python's isalpha() method combined with list comprehension provides an efficient solution.
Understanding isalpha()
The isalpha() method returns True if all characters in a string are alphabetic (a-z, A-Z) and there is at least one character. It returns False if the string contains numbers, spaces, or special characters.
Example
Here's how to filter rows containing only alphabetic strings:
data = [["python", "is", "best"], ["abc123", "good"], ["abc def ghij"], ["abc2", "gpqr"]]
print("Original list:")
print(data)
# Filter rows where all elements contain only alphabets
filtered_result = [row for row in data if all(element.isalpha() for element in row)]
print("\nFiltered result:")
print(filtered_result)
The output of the above code is:
Original list: [['python', 'is', 'best'], ['abc123', 'good'], ['abc def ghij'], ['abc2', 'gpqr']] Filtered result: [['python', 'is', 'best']]
How It Works
The solution uses a list comprehension with the all() function:
all(element.isalpha() for element in row)- checks if every element in a row contains only alphabetselement.isalpha()- returnsFalsefor strings with numbers, spaces, or special charactersOnly rows where all elements pass the alphabetic test are included in the result
Testing Different Cases
Let's see how isalpha() behaves with different string types:
test_strings = ["hello", "abc123", "abc def", "ABC", ""]
for string in test_strings:
print(f"'{string}'.isalpha() = {string.isalpha()}")
'hello'.isalpha() = True 'abc123'.isalpha() = False 'abc def'.isalpha() = False 'ABC'.isalpha() = True ''.isalpha() = False
Alternative Using Filter Function
You can also use the filter() function for the same result:
data = [["python", "is", "best"], ["abc123", "good"], ["hello", "world"]]
# Using filter function
filtered_result = list(filter(lambda row: all(element.isalpha() for element in row), data))
print("Result using filter():")
print(filtered_result)
Result using filter(): [['python', 'is', 'best'], ['hello', 'world']]
Conclusion
Use isalpha() with all() in list comprehension to filter rows containing only alphabetic strings. This approach efficiently handles nested lists and provides clean, readable code for text processing tasks.
