AJP AJP - 5 months ago 8
Python Question

Nested for loop to match vowels by iterating over strings and lists

I am trying to loop over a list, and match each character in that list with characters in a string:

wordlist = ['big', 'cats', 'like', 'really']
vowels = "aeiou"
count = 0
for i in range(len(wordlist)):
for j in vowels:
if j in wordlist[i]:
count +=1
print(j,'occurs', count,'times')


to return
"a" occurs 2 times.
for each vowel but this does not work. What am i doing wrong?

Answer

Try this:

wordlist = ['big', 'cats', 'like', 'really']
vowels = "aeiou"        
for v in vowels:
    count = 0
    for word in wordlist:
        if v in word:
            count += 1
    print(v,'occurs', count, 'times')

results:

a occurs 2 times
e occurs 2 times
i occurs 2 times
o occurs 0 times
u occurs 0 times
Comments