Open In App

Find the List elements starting with specific letter – Python

Last Updated : 19 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal is to filter the elements of a list that start with a specific letter, such as ‘P’. For example, in the list [‘Python’, ‘Java’, ‘C++’, ‘PHP’], we aim to find the elements that begin with the letter ‘P’, resulting in the filtered list [‘Python’, ‘PHP’]. Let’s explore different approaches to achieve this.

Using list comprehension

List comprehension provides a quick way to filter names by comparing the first letter of each string after converting it to lowercase. It is particularly effective for simple, case-insensitive checks and works well for small to medium-sized lists.

Python
a = ['Akash', 'Nikhil', 'Manjeet', 'akshat']

# check letter
b = 'A'

res = [i for i in a if i[0].lower() == b.lower()]
print(res)

Output
['Akash', 'akshat']

Explanation: List comprehension iterates through each name in the list and checks whether the first character of each name, when converted to lowercase, matches the given letter b, also converted to lowercase.

Using filter()

Filter() with a lambda makes it easy to filter names by their first letter, ignoring case. It’s a clean, modular approach that works great in functional programming, especially when chaining operations.

Python
a = ['Akash', 'Nikhil', 'Manjeet', 'akshat']

# check letter
b = 'A'

res = list(filter(lambda i: i[0].lower() == b.lower(), a))
print(res)

Output
['Akash', 'akshat']

Explanation: filter() with a lambda filters names in a where the first character, converted to lowercase, matches the lowercase version of b. The result is an iterator, which is then converted to a list and stored in res.

Using startswith()

startswith() method check if a name begins with a given prefix, converting both strings to lowercase to make it case-insensitive. It’s great for matching more than just the first character, and the code remains highly readable and easy to maintain.

Python
a = ['Akash', 'Nikhil', 'Manjeet', 'akshat']

# check letter
b = 'A'

res = [i for i in a if i.lower().startswith(b.lower())]
print(res)

Output
['Akash', 'akshat']

Explanation: List comprehension filters names in a that start with the letter b, using startswith() for a case-insensitive match and stores the results in res.

Using str.casefold()

This method is similar to lower() but offers more aggressive Unicode support, making it ideal for handling international or multilingual names. It effectively manages special characters, such as the German “ß”, ensuring accurate case-insensitive matching.

Python
a = ['Akash', 'Nikhil', 'Manjeet', 'akshat']

# check letter
b = 'A'

res = [i for i in a if i[0].casefold() == b.casefold()]
print(res)

Output
['Akash', 'akshat']

Explanation: List comprehension filters names in a whose first character matches b, using casefold() for case-insensitive comparison.



Next Article
Practice Tags :

Similar Reads