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

Alexander Anderson
Alexander Anderson
1,325 Points

Disemvowel - Why is my code missing vowels?

I'm having a hard time understanding why my code is only removing some vowels but not all of them.

I've figured out that it works correctly if I replace 'word_list' on line 4 with 'word'. Could someone explain why it works when the for-loop is iterating through 'word' (which is just the original string passed to the function as an argument?) but won't work when iterating through 'word_list'?

Why would it work when iterating through the string but not the list?

Hope this makes sense.

Thanks

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

    word = ''.join(word_list)
    return word

1 Answer

Steven Parker
Steven Parker
231,248 Points

Altering an iterable that controls a loop can cause the loop to skip items when the indexes suddenly change.

A common fix is to use a copy of the iterable to control the loop, which is essentially what the original string is for the purpose of the loop.

Alexander Anderson
Alexander Anderson
1,325 Points

Hi Steven. That's great, thanks for your help.