Find the list elements starting with specific letter in Python


In this article we will find all those elements from a list which start with specific letter.

With index and lower

We use the lower function so that the test later can match with the first letter of the the elements in the list irrespective of the case. Then we use the index at 0 so that the first letter of the elements in a list are compared with the test letter.

Example

 Live Demo

listA = ['Mon', 'Tue', 'Wed', 'Thu']
# Test with letter
test = 'T'
# printing original list
print("Given list\n " ,listA)
# using lower and idx
res = [idx for idx in listA if idx[0].lower() == test.lower()]
# print result
print("List elements starting with matching letter:\n " ,res)

Output

Running the above code gives us the following result −

Given list
['Mon', 'Tue', 'Wed', 'Thu']
List elements starting with matching letter:
['Tue', 'Thu']

With startswith

It is a very straight forward approach in which we use a function startswith. This function Returns true if the element starts with the test letter else it returns false.

Example

 Live Demo

listA = ['Mon', 'Tue', 'Wed', 'Thu']
# Test with letter
test = 'T'
# printing original list
print("Given list\n " ,listA)
# using startswith
res = [idx for idx in listA if idx.lower().startswith(test.lower())]
# print result
print("List elements starting with matching letter:\n " ,res)

Output

Running the above code gives us the following result −

Given list
['Mon', 'Tue', 'Wed', 'Thu']
List elements starting with matching letter:
['Tue', 'Thu']

Updated on: 04-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements