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

Garrett Hughes
seal-mask
.a{fill-rule:evenodd;}techdegree
Garrett Hughes
Python Development Techdegree Student 32,971 Points

Why is it removing random letters?

I know my code's far from perfect. When I run it on Repl.it with the word was "backpack" I get back "bkpk". Why is it removing the letter C?

disemvowel.py
def disemvowel(word):
    word = word.lower()
    split = list(word)
    vowels = ['a','e','i','o','u']
    new_word = []
    for x in split:
        if x in vowels:
            split.remove(x)
        else:
            new_word.append(x)
    print("".join(new_word))

disemvowel("backpack")

1 Answer

Steven Parker
Steven Parker
231,236 Points

:warning: Never modify a variable that you are using to iterate in a loop.

It only looks random. But what's happening is that when you remove items from the thing you are using to control the loop, the performance of the loop is affected. Possible ways to address this would include:

  • iterating using a copy of the item you will be changing in the loop
  • building a new result in the loop instead of modifying the original
  • using a different kind of loop