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
Find the list elements starting with specific letter in Python
In this article, we will explore different methods to find all elements from a list that start with a specific letter. Python provides several approaches to achieve this efficiently.
Using Index and lower()
This method uses the lower() function to make the comparison case-insensitive. We access the first character of each element using index [0] and compare it with the test letter ?
days = ['Mon', 'Tue', 'Wed', 'Thu']
test_letter = 'T'
print("Given list:")
print(days)
# Using lower() and index to find elements starting with specific letter
result = [item for item in days if item[0].lower() == test_letter.lower()]
print("List elements starting with matching letter:")
print(result)
Given list: ['Mon', 'Tue', 'Wed', 'Thu'] List elements starting with matching letter: ['Tue', 'Thu']
Using startswith()
The startswith() method is a more straightforward approach. It returns True if the string starts with the specified prefix, otherwise False ?
days = ['Mon', 'Tue', 'Wed', 'Thu']
test_letter = 'T'
print("Given list:")
print(days)
# Using startswith() method
result = [item for item in days if item.lower().startswith(test_letter.lower())]
print("List elements starting with matching letter:")
print(result)
Given list: ['Mon', 'Tue', 'Wed', 'Thu'] List elements starting with matching letter: ['Tue', 'Thu']
Using filter() Function
The filter() function provides a functional programming approach to filter elements based on a condition ?
days = ['Mon', 'Tue', 'Wed', 'Thu']
test_letter = 'T'
print("Given list:")
print(days)
# Using filter() with lambda function
result = list(filter(lambda x: x.lower().startswith(test_letter.lower()), days))
print("List elements starting with matching letter:")
print(result)
Given list: ['Mon', 'Tue', 'Wed', 'Thu'] List elements starting with matching letter: ['Tue', 'Thu']
Comparison
| Method | Readability | Best For |
|---|---|---|
| Index [0] | Good | Single character matching |
| startswith() | Excellent | Prefix matching (single or multiple characters) |
| filter() | Good | Functional programming style |
Conclusion
Use startswith() for the most readable and flexible solution. The index method works well for single characters, while filter() offers a functional programming approach.
