Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Lists Disemvowel

Hai Phan
Hai Phan
2,442 Points

I can't remove all vowel from a word with my function, just some of them is!

Here is my code:

def disemvowel(word):
    string = list(word)
    for letter in string: 
        for vowel in ["a","e","i","o","u"]:
            if letter.lower() == vowel:
                try:
                    string.remove(letter)
                except ValueError:
                    continue
    word = "".join(string)        
    return word

When I enter something like "AEoiuPOKg" I expected to receive "PKg" but what I got is "EiPKg"! 'A', 'o', 'u' , 'O' are remove because they are vowel but I don't know why 'E' and 'i' is still here. Can someone help, please!

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

It is because when you are removing a letter it is modifying the string list and you will skip the letter following a remove since the index has changed.

You need to do the remove on a copy of the list so that your for loop goes over each value.

Try:

def disemvowel(word):
    string = list(word)
    string_copy = string.copy()
    for letter in string: 
        for vowel in ["a","e","i","o","u"]:
            if letter.lower() == vowel:
                try:
                    string_copy.remove(letter)
                except ValueError:
                    continue
    word = "".join(string_copy)        
    return word     

print(disemvowel("AEoiuPOKg"))
Hai Phan
Hai Phan
2,442 Points

I got it! Thank you so much!