8/15 help with my code


#1

Hello, can you tell me please why my code is not working? When submitted, I get :
Oops, try again. Your function fails on anti_vowel("Hey look Words!"). It returns "Hy lk Words!" when it should return "Hy lk Wrds!".

    def anti_vowel(text):
        words = list(text)
        for letter in words:
            if letter in "AEIOUaeiou":
                words.remove(letter)
        return ''.join(words)

Anti vowel,not working on the third 'o'
#2

Hi,

you iterate over the same list you remove letters from. The .remove() function removes the first match it finds.

So for words = list("Hey look Words!"), the first letter is "H". It's not a vowel so we just move on to the second letter.
The second letter is "e", a vowel and the first "e" in the list will be removed. That means words is now equal to
['H', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'W', 'o', 'r', 'd', 's', '!'].
Now we move on the third letter, in the original words list that would have been y but in our new list it's " ".

So everytime a letter is removed we jump over the next letter. For ['H', 'e', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'W', 'o', 'r', 'd', 's', '!'], we jump over the 'y' after 'e', the 'o' after the first 'o', and the 'r' after the third 'o'. This of course only matters if we jump over a vowel because only those need to be removed. What happens is that the second 'o' won't be checked for removal, but when the third 'o' is checked the second 'o' gets removed, because it slipped through the test.


#3

Oh I see, at first I thought of creating a new list to iterate over the original list without modifying it, then I think I found easier, is this good ? :

def anti_vowel(text):
    words = list(text)
    for letter in text:
        if letter in "AEIOUaeiou":
            words.remove(letter)
    return ''.join(words)

#4

Seems fine to me, good idea to use the original string to loop over.