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 to print element with maximum vowels from a List
When it is required to print element with maximum vowels from a list, we can iterate through each word and count vowels using list comprehension or other methods.
Example
Below is a demonstration of the same ?
words = ["this", "week", "is", "going", "great"]
print("The list is :")
print(words)
result = ""
max_vowel_count = 0
vowels = ['a', 'e', 'i', 'o', 'u']
for word in words:
vowel_count = len([char for char in word.lower() if char in vowels])
if vowel_count > max_vowel_count:
max_vowel_count = vowel_count
result = word
print("The result is :")
print(result)
Output
The list is : ['this', 'week', 'is', 'going', 'great'] The result is : going
Using max() Function
We can also use the built-in max() function with a key parameter for a more concise solution ?
words = ["this", "week", "is", "going", "great"]
def count_vowels(word):
vowels = "aeiou"
return sum(1 for char in word.lower() if char in vowels)
result = max(words, key=count_vowels)
print("The list is :")
print(words)
print("Word with maximum vowels :")
print(result)
print("Number of vowels :", count_vowels(result))
The list is : ['this', 'week', 'is', 'going', 'great'] Word with maximum vowels : going Number of vowels : 3
Explanation
- A list of strings is defined and displayed on the console.
- We iterate through each word and count vowels using list comprehension.
- The
lower()method ensures case-insensitive vowel counting. - We track the word with maximum vowel count and update it when a higher count is found.
- The
max()function approach uses a custom key function to find the word with most vowels directly. - The result is displayed on the console.
Conclusion
Use list comprehension with a loop to manually track the maximum, or use max() with a key function for cleaner code. Both methods effectively find the word with the most vowels.
Advertisements
