Looping num.pop() infinitely in Python using .pop() method

Feedback


Question:

Here’s the code:

vowels = ['a','e','i','o','u']
def anti_vowel(text):
    tlength = len(text)
    words = []
    result = ""
    for word in range(len(text)):
        words.append(text[word])
        print words
    for index, word in enumerate(words):
        if word.lower() in vowels:
            words.pop(index)
    for old_word in words:
        result += str(old_word)
    return result
print anti_vowel("Hey look words!")

The desired outcome is “Hy lk wrds!” but the current outcome is “Hy lok words!

I’m struggling to understand why the loop is not including the ‘o’ at index 5 in the words list. Although I could use a different method by creating a separate list for non-vowel words and then combining them, my focus is on finding a solution for the current code to achieve the intended outcome.


Solution:

As you remove certain characters, the

index

still relies on them, causing the vowels to no longer be in their expected index.

It is advisable to avoid modifying a list within a for loop and instead, create a fresh one.

def anti_vowel(text):
    words = []
    for character in text:
        if not (character.lower() in vowels or character.upper() in vowels):
            words.append(character)
    return ''.join(words)

or with generator expression:

def anti_vowel(text):
    return ''.join(c for c in text if c.lower() not in vowels)

To remove individual elements, a while loop must be utilized.

def anti_vowel(text):
    text = list(text)
    index = 0
    while index < len(text):
        if text[index].lower() in vowels:
            del text[index]
        else:
            index += 1
    return ''.join(text)

Frequently Asked Questions