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 alphabets

  • element.isalpha() - returns False for strings with numbers, spaces, or special characters

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

Updated on: 2026-03-26T02:39:39+05:30

538 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements