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

Vowels Chanllenge

I checked several discussion in community and I still can't not pass with below code. It showed "Your code took too long to run" Appreciated to know how to revise the code.

disemvowel.py
def disemvowel(word):
    vowels = ["a", "e", "i", "o", "u"]
    word = list(word)
    for letter in word:
        if letter.lower() not in vowels:
            word.append(letter)
    word = "".join(word)
    return word

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! The problem is that for any word that contains a letter not in the vowels list, your loop will run infinitely.

Here's the part of your code that's doing that:

    for letter in word:  #for every letter in the word,
        if letter.lower() not in vowels: #if the letter is not a vowel
            word.append(letter) #append it to the original word

But if we were to send in the word "tree", during the first iteration it will look at that "t". It is not a vowel, so it will be appended onto "tree". At this point, you would have "treet". During the second iteration, it will see "r" and append it as well. Now you have "treetr". This means that for every iteration where the letter is not a vowel, word will be growing in size by another letter that is guaranteed not to be a vowel. Thus, it results in an infinite loop.

As a general rule, it is a good idea to try not to mutate the thing you're looping over during the execution of the loop.

I reworked your code a bit so that it passes and looks similar to yours. Take a look:

def disemvowel(word):
    vowels = ["a", "e", "i", "o", "u"]
    new_word = [] #set up a blank list to hold letters that aren't vowels
    for letter in word:  #for every letter in the word
        if letter.lower() not in vowels:  #if the lower case version is not a vowel
            new_word.append(letter)  #append it to the new list
    new_word = "".join(new_word)  #join our new list so that it is now a string
    return new_word  #return the results of our consonant only list

Hope this helps! :sparkles:

Thanks for your explanation! It really help!