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

Manal El
Manal El
3,563 Points

Why my code isn't working correctly?

I have wrote this code where it detects the other vowels but not "e" although I have explicitly stated it in the list, I know I'm missing something but I don't know what is it ! any help would be greatly appreciated :)

disemvowel.py
def disemvowel(word):
    li = list(word)
    for i in li:
        if i.lower() in ["i", "a", "o","u", "e"]:
            print(i)
            li.remove(i)
            word = ''.join(li)
    return word




print(disemvowel("XieU"))

1 Answer

Hey Manal, your code is actually basically correct. There isn't anything wrong with the logic of the function you have written. The reason why the function is not returning the correct result is because you are simultaneously looping over a list and altering it. Remember back to the course on lists and the explanation about looping over mutable iterables: when you are going to alter an iterable while looping over it, it is required that you actually loop over a copy of the iterable, rather than the iterable itself. Looping over an iterable and simultaneously altering it produces strange results.

Currently your for loop looks like this: for i in li.... Instead, use for i in li.copy() and then keep everything else the same and it will work. Happy coding!

Manal El
Manal El
3,563 Points

Thanks a lot Michael ! should always remember to loop over a copy of mutable objects ;)