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
Selected Reading
Python Program that extract words starting with Vowel From A list
When you need to extract words starting with vowels from a list, Python offers several approaches. You can use iteration with the startswith() method, list comprehensions, or the filter() function.
Using Loop with startswith() Method
This approach uses a flag to check if each word starts with any vowel ?
words = ["abc", "phy", "and", "okay", "educate", "learn", "code"]
print("The list is:")
print(words)
result = []
vowels = "aeiou"
print("The vowels are:", vowels)
for word in words:
flag = False
for vowel in vowels:
if word.startswith(vowel):
flag = True
break
if flag:
result.append(word)
print("The result is:")
print(result)
The list is: ['abc', 'phy', 'and', 'okay', 'educate', 'learn', 'code'] The vowels are: aeiou The result is: ['abc', 'and', 'okay', 'educate']
Using List Comprehension
A more concise approach using list comprehension with the any() function ?
words = ["abc", "phy", "and", "okay", "educate", "learn", "code"]
vowels = "aeiou"
result = [word for word in words if any(word.startswith(vowel) for vowel in vowels)]
print("Words starting with vowels:", result)
Words starting with vowels: ['abc', 'and', 'okay', 'educate']
Using filter() Function
Using filter() with a lambda function to check vowel conditions ?
words = ["abc", "phy", "and", "okay", "educate", "learn", "code"]
vowels = "aeiouAEIOU" # Include uppercase vowels
result = list(filter(lambda word: word[0].lower() in vowels, words))
print("Words starting with vowels:", result)
Words starting with vowels: ['abc', 'and', 'okay', 'educate']
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Loop with flag | Good | Moderate | Learning/debugging |
| List comprehension | Excellent | Good | Most cases |
| filter() function | Good | Good | Functional programming |
How It Works
- Loop method: Uses a flag variable to track if any vowel matches the first character
-
List comprehension: Uses
any()to check if the word starts with any vowel - Filter method: Checks if the first character (converted to lowercase) exists in the vowels string
Conclusion
List comprehension with any() provides the most readable and efficient solution. Use the loop method for learning purposes and filter() for functional programming approaches.
Advertisements
