Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Lists Disemvowel

Sadettin Esenlik
Sadettin Esenlik
1,423 Points

Cannot pass challenge even though my answer is correct

I' m running the attached python script on my system and it returns disemvoweled word as expected, but when I click recheck work, I get that my code is wrong. What am I doing wrong ?

disemvowel.py
def disemvowel(word):
    vowels = ["a","e","i","o","u"]
    vowels = vowels + list("".join(vowels).upper())
    letters = list(word)
    for letter in letters:
        if letter in vowels:
            letters.remove(letter)

    word = "".join(letters)
    return word

1 Answer

andren
andren
28,520 Points

The problem is that you are removing items from a list while looping over that same list. Doing that will lead to items being moved around in the list while it is being looped over, which will result in some item being skipped by the loop.

The code mainly fails in cases where a vowel appears repeatedly, for example if you pass the string "aaaa" to your function it will return "aa" which is clearly not correct.

This can be fixed by using the string itself for the loop source instead of the list, like this:

def disemvowel(word):
    vowels = ["a","e","i","o","u"]
    vowels = vowels + list("".join(vowels).upper())
    letters = list(word)
    for letter in word:
        if letter in vowels:
            letters.remove(letter)

    word = "".join(letters)
    return word

Also just as a tip you can perform this task without having both lowercase and uppercase versions in the vowel list by calling lower on the letter as you compare it to the vowels list. Like this:

def disemvowel(word):
    vowels = ["a","e","i","o","u"]
    letters = list(word)
    for letter in word:
        if letter.lower() in vowels:
            letters.remove(letter)

    word = "".join(letters)
    return word

Which at least to me feels a bit cleaner than adding more letters to the vowels list.

Sadettin Esenlik
Sadettin Esenlik
1,423 Points

Thanks for the answer. I see where I was mistaken now.