Search code examples
pythonstringpython-3.xlistlist-comprehension

Count Vowels from a word list and return the number as a list


I just want to define a function, number_of_vowels, that returns the number of vowels in a string.

My code is below:

vowels='aeiou'
def number_of_vowels(word):
    return[len([letter.lower() for letter in word if letter in vowels])]
names = ["Ben", "April", "Zaber", "Alexis", "McJagger", "J.J.", "Madonna"]
number_of_vowels(names)

I only got [0] in my result. Not sure why


Solution

  • You are feeding a list but your logic is appropriate for a single string only:

    number_of_vowels('Bean')  # [2]
    

    You need to either adjust the input to your function, or modify your function to calculate the number of vowels for each element of your list. Since you wish the output to be a list of numbers, I assume you're looking for the second option.

    To do this, just add an extra for clause in your list comprehension:

    def number_of_vowels(words):
        return [len([letter for letter in word if letter.lower() in vowels]) \
                for word in words]
    
    number_of_vowels(names)  # [1, 2, 2, 3, 2, 0, 3]
    

    However, note the intermediary lists are not required. You can use sum with a generator expression instead, taking advantage of the fact True == 1 and False == 0:

    vowels = set('aeiou')
    
    def number_of_vowels(words):
        return [sum(letter.lower() in vowels for letter in word) for word in words]
    
    number_of_vowels(names)  # [1, 2, 2, 3, 2, 0, 3]
    

    Notice a couple of further changes to improve your algorithm:

    1. Check for letter.lower() in vowels instead of just creating a list of lower-case letters. Otherwise vowels as capital letters, e.g. in "April", will be ignored.
    2. Convert your vowels to set for O(1) lookup complexity.