Loop in list and find the vowels for each string

Hello everyone.

I am working on this excersis were I have to count the vowels for every string in a list. It is a list with country names. I need to wrap it up in a function and use the For Loop to count al the vowels for every country name… Already tried some coding but things didt work out that well. This is the code that I already wrote.

def most_vowels(countries):
   countries = [countrie.lower() for countrie in countries]
   vowels = ['aeiou']
   count = 0
   for i in countries:
    if vowels in len(countries[0]):
        count = count + 1
        return (count)


Thanks for taking the time to help me.

Couple of things.

  1. You can’t count vowels in the length of an array vowels in len(countries[0]).
  2. There is no reason to have the vowels also in a list:[ 'aeiou']. I’d either do a list of characters or just iterate the string directly.
  3. strings have a count method you could use to count how many times a substring is in a string. Built-in Types — Python 3.11.2 documentation
  4. You could also use map to perform a function for so many iterations: Built-in Functions — Python 3.11.2 documentation
  5. You could use sum to sum up all the results of the multiple calls performed in map: Built-in Functions — Python 3.11.2 documentation
  6. Lastly, I don’t understand if the function is supposed to return all the vowels in all the countries or just the number of vowels in the country that has the most vowels. You seem to return on the very first country, so I don’t think this is what you actually want to do. I’m going to assume the country with the most values is what it calculates and then returns that value.

So, what the below code does is map iterates the characters in aeiou calling count on the given string for each vowel. All the counts are returned, and sum adds them all together.

>>> sum(map('alphabet'.count, 'aeiou'))

So you could just replace the arbitrary string alphabet with each country and add the total result to your global count:

def most_vowels(countries):
    """Returns the country with the greatest number of vowels."""

    vowels = 'aeiou'
    count = 0
    for country in countries:
        result = sum(map(country.lower().count, vowels))
        if result > count:
            count = result
    return count

print(most_vowels(['Germany', 'France', 'Egypt', 'United States of America']))
1 Like
num_vowels= {w: sum(w.lower().count(v) for v in vowels) for w in words}

Here’s an edge case for you: How many vowels in “Python”?

Thank you so much for this comment.
I will have a good night of sleep and tommorow check all the feedback you sended to me. But in a short glance I can see this is very helpful.

It needs to return all the vowel for each different country:

Like :

Afghanistan 4
Aruba 3
Netherlands 3

In future if I can figure this out I will have to make a top 3 of countries with the most vowels. But first I will focus on this subject.

Then you may store it in a dictionary like what @abessman suggested, but the logic to get the vowel count for a country is the same.

Dictionary is in about two chapters in the course. Would be cool but need to figure it out in the other way. Will give it a shot tommorow. If it worked I will let you know in the thread so everyone can learn from it.

Create a list of lists if you don’t know how to use dictionaries and wish to stick with what you know.

results = []
results.append([country, vowel_count])

Using the concept of what you are tying and keeping things simple, you could code it like this:

def vowels(word):
    count = 0
    vowels = ['a', 'e', 'i', 'o', 'u']
    for alpha in word.lower():
        if alpha in vowels:
            count += 1
    return count

word_list = ["Afghanistan", "Aruba", "Netherlands"]

for word in word_list:
    n_vowels = vowels(word)
    print(f"{word} {n_vowels}")

You could also expand on this so that, in the end, you output, not only the individual vowel count, but also the country (or any word) in the list that contains the most vowels.

What has been given to you in this thread is all good, but (IMHO) you should first learn the basics of Python coding before trying to master more advanced concepts; my guess is that right now you’re learning about data types (of which a list object is one), loops and functions.

I don’t see the need for your list comprehension in your function, because you can simply give the function one word at a time, rather than an entire list, then have a new function to deal with the resulting output:

Afghanistan 4
Aruba 3
Netherlands 3

It maybe that you have more code, but readability trumps complexity: get each part working correctly, before moving on to the next and have one function for each operation.

Again, it’s just my opinion and each coder will have their own take on this and their own style.

Edit done for typo correction.

1 Like

No youre completly right in youre answer Rob.
The problem at this moment is that I started a online course for Data Analitics.
In the course I get like a little fork to eat the cake and the recipe and cake baking I have to do for myself. I am not used to studie in this way.
For it is hard because I get lost in details very easy.

Thats why I came to this forum. With all youre help it will work. Now I found a way to collect data to make things possible. I will start at the beginning and from there I will built bigger. Untill I get the concept needed.

Not too sure if you have a coding background [your use of return (count) would suggest C or a derivative of]. It would help, if you have, but if not, it’s not a deal breaker, as many coders have started with Python; a very popular coding language and becoming more so as the years roll on.

A very good site to BM is Dan’s Real Python dot com:

You’ll find a huge amount of free content as well as the paid-for content.

The fact that you’re trying and posting your code, rather than simply expecting others to code for you, is a positive sign: the only way to learn how to code, is to code.

I am like a Rookie Rookie… complete beginner.
Worked for long time as a nurse.
But got burn out… so have to change my career for the best.

Really thanks allot on the info.
Started all over…
with the begin of the theoretical part for For Loops.

Can integrate all you’re info into it!!

Stick with it and happy coding; you’ll get there.

Tip: drop the habit of using parentheses on the return statement of functions, unless you need to return a collection of values, with different object names, e.g return (a, b), that is the say: only use parentheses with a return for good reason.

Edit to add: sorry, I should say that return (a, b) is the same as return a, b: a tuple object will be returned, but return [a, b] will return a list object; there are other combinations, but that’s something that you’ll learn about, all in good time.

1 Like

I started all over with the For Loops. Was down with covid for some weeks.
Need to start over to understand the full theorie of the For Loop.

I need to write a function (def) and from there on I need to count the vowels in a list called countries.
But because I am starting all over I just want to write a function were all countries are written like this



I already noticed that the return function is breaking my loop. In this example it is only printing the last value: Zimbabwe. If I tab the return function I only get the Vlaue Afghanistan.
I will have to change the return function in to something else. Also found some information about the yield function. But can get it working.

Some (simple) advice is needed.

def most_vowels(countries):
    for organize in countries:
        if organize in countries:

print (most_vowels(countries))

This is the code I have been writing.

The trick to understanding code is to use good names for variables. What is your variable “organize” supposed to mean?

A better name would be “country”.

So you have:

def most_vowels(countries):
    for organize in countries:
        if organize in countries:

The for-loop starts going through the list of countries, one at a time.

  • The first country is “Afghanistan”, so it sets the variable organize (ugh!) to “Afghanistan”.
  • Then it checks to see if that country, “Afghanistan”, is in the list of countries.
    • Of course it is! It came from the list of countries, to it will always be in the list of countries.
    • So you then return that country, and exit the loop.

At no point do you count how many vowels are in the word. Before you can find the country with the most vowels, first you need a function to count the vowels.

There are lots of ways to do this. Here is one way:

def count_vowels(word):
    # Return the number of vowels in the word.
    num = 0
    for char in word:
        # Is the character a vowel?
    return num

You need to finish the function so that it counts vowels. Remember that Python is case-sensitive, so “e” and “E” are considered different.

Once you have written that function, test it:

print(count_vowels("South Africa"))

Does it print 5, 2, 3, 2, 2? If so, then it is working, otherwise there is a bug in the function.