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

Disemvowel code is giving inconsistent results.

It seems to me that the code is legit. I don't understand why it is picking and choosing certain vowels to remove from the entered word. Can anyone spot the culprit?

def disemvowel(word):
    word_list = list(word)
    vowels = ["a","i","e","o","u"]
    for letter in word_list:
      if letter.lower() in vowels:
          word_list.remove(letter)
    word = "".join(word_list)
    return word

#Input: ZazaSKMoACpiuziaUxxaAEU
#Output: ZzSKMACpuzxxaAU

1 Answer

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

you are modifying a list while looping through it. this results in skipped elements. when remove is called, it removes the element, then shifts remaining elements to the left. the loop moves on to the next element however, so some get skipped. one way to fix is to make a copy and loop through that while modifying the original, or vice versa.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

The quickest way to may a copy is with slice notation:

for letter in word_list[:]:

It makes sense now. Thanks a lot @JamesSouth and @ChrisFreeman3.