8. Anti-Vowel: For loop skipping an index?


#1



There are no error messages. The For loop just skips over an index for unknown reasons:
['H', 'e', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'w', 'o', 'r', 'd', 's', '!']
['H', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'w', 'o', 'r', 'd', 's', '!']
['H', 'y', ' ', 'l', 'o', 'k', ' ', 'w', 'o', 'r', 'd', 's', '!']
['H', 'y', ' ', 'l', 'o', 'k', ' ', 'w', 'r', 'd', 's', '!']
Hy lok wrds!


I expected the For loop to actually fully iterate through the list.


def anti_vowel(text):
    phrase = []
    result = ""
    for c in text:
        phrase.append(c)
    print phrase
    for i, c in enumerate(phrase):
        if str(c).upper() == "A" or str(c).upper() == "E" or str(c).upper() == "I" or str(c).upper() == "O" or str(c).upper() == "U":
            del phrase[i]
            print phrase
    for c in phrase:
        result += str(c)
    return result
    
print anti_vowel("Hey look words!")


#2

@wirsindallein: Most likely because whenever you use del, you'll delete the element at that given position so it won't exist anymore.
Due to that operation, your decreasing the size of your list and such will end up skipping vowels who are "close" to each other such as look, it will get the first "o", will decrement the length of your list, your second "o" will stay in the place of your first "o" and your code will continue right after the second "o".

Before deleting:

L   O   O   K
1 | 2 | 3 | 4

After deleting:

L   O   K
1 | 2 | 3

It will continue from the first position right after the remaning "o".

Hope I was clear, if not, I'll find another way to explain!

Edit: Difference between del, remove and pop on lists