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

Matthew Kiggen
Matthew Kiggen
2,423 Points

Why does my code not remove the second occurrence of the vowel?

If I use "aaeeiioouu" as my word

I get "aeiou" as my return

disemvowel.py
def disemvowel(word):
    word = (list(word))
    for char in word:
        if char == "a":
            word.remove("a")
        elif char == "e":
            word.remove("e")
        elif char == "i":
            word.remove("i")
        elif char == "o":
            word.remove("o")
        elif char == "u":
            word.remove("u")
    return "".join(word)
Matthew Kiggen
Matthew Kiggen
2,423 Points

But, if I use "this is a string" as my word it removes all vowels

1 Answer

Ignazio Calo
PLUS
Ignazio Calo
Courses Plus Student 1,819 Points

The problem is that your are modify the string during the process. Follow me:

  1. The input string is aaeeiioouu.
  2. The first iteration the code check the first letter in this string a. Because it's an a is removed from the word.
  3. Now the string is aeeiioouu.
  4. Next iteration of the for loop, now the code checks the second element of the string, the 'e' :) so you just skipped the second 'a' therefore is not removed.

Solution: Never edit an array during a for-loop on the same array. One possible solution is to create a copy of the Array.

def disemvowel(word):
    word = (list(word))
    copy = word[:]
    for char in word:
        if char == "a":
            copy.remove("a")
        elif char == "e":
            copy.remove("e")
        elif char == "i":
            copy.remove("i")
        elif char == "o":
            copy.remove("o")
        elif char == "u":
            copy.remove("u")
    return "".join(copy)

print(disemvowel("aaeeiioouuff"))
Matthew Kiggen
Matthew Kiggen
2,423 Points

Awesome, thanks for the help!