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 trialGarrett Hughes
Python Development Techdegree Student 32,971 PointsWhy 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?
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
231,269 PointsNever 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
Garrett Hughes
Python Development Techdegree Student 32,971 PointsGarrett Hughes
Python Development Techdegree Student 32,971 PointsAhhh thank you :D