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

Bozhong Tao
Bozhong Tao
18,365 Points

Why is my code not returning the right outcome?(always miss a letter)

Hi , thanks for checking up on my code :)

my logic is:

  1. turn the word into a list

  2. for every letter in the word, compare it to every vowel in the vowels list (vowels = ['a', 'e', 'i', 'o', 'u'])

  3. I will compare both the upper case of vowels and lower case(them-self)

  4. if the letter matches(no matter lower case or upper case), remove it from the word. start from the next letter in word

  5. then join the processed list back into a string and return as the word

Somehow I always miss a vowel, I don't know what caused this, some help would be really appreciated!

disemvowel.py
def disemvowel(word):
    vowels = ['a', 'e', 'i', 'o', 'u']

    word = list(word)

    for letter in word:
        for vow in vowels:    
            if vow.upper() == letter or vow == letter:
                word.remove(letter)                

    word = ''.join(word)
    return word

3 Answers

Steven Parker
Steven Parker
229,786 Points

This is a common issue and it's a result of modifying an iterator inside the loop that it is controlling. It causes elements to be skipped in the loop.

One easy remedy is to use a copy of the list as the iterator for the loop.

Bozhong Tao
Bozhong Tao
18,365 Points

I see, so when the loop modify the word list on the go, it will change the index of the letter which will cause the skip issue right? That make sense!

Thanks again @stevenparker !! :D

Steven Parker
Steven Parker
229,786 Points

You got it. And if you were adding to the list it could cause the loop to repeat items.

Bozhong Tao
Bozhong Tao
18,365 Points

Thanks for the extra tip. One less mine for me to step on in future codes! Cheers Steven :)

PS. this might be useful for anyone who has similar issues and try to 'copy' the list for iteration - https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list