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

Somebody, please tell me why my answer is it not correct?

I've tried the function that I wrote in a python shell and it's working as it is supposed to be. But in the code challenge, it's incorrect. someone help me out I'm stuck here.

disemvowel.py
def disemvowel(word):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
    word_list = list(word)
    for alphabet in word_list:
        if alphabet in vowels:
            word_list.remove(alphabet)
        else:
            pass
    word = "".join(word_list)
    return word

1 Answer

Ryan S
Ryan S
27,276 Points

Hi Jasmeet,

The issue is that you are modifying the list as you are looping through it. This can cause some unwanted behavior in the indexing of the list.

If you find a vowel then remove it, the index values all shift and you end up skipping the next item. So if you have 2 vowels in a row, then you will miss the next vowel. Have you tested your code with a word that has 2 consecutive vowels?

To deal with this, you can simply loop through a copy of the list, but keep modifying the original list. Using slices is a good way to accomplish this.

def disemvowel(word):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
    word_list = list(word)
    for alphabet in word_list[:]:  # Create sliced copy of list:
        if alphabet in vowels:
            word_list.remove(alphabet)
        else:
            pass
    word = "".join(word_list)
    return word

Hope this helps.

Thanks a lot, Ryan.