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 trialMatthew Kiggen
2,423 PointsWhy does my code not remove the second occurrence of the vowel?
If I use "aaeeiioouu" as my word
I get "aeiou" as my return
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)
1 Answer
Ignazio Calo
Courses Plus Student 1,819 PointsThe problem is that your are modify the string during the process. Follow me:
- The input string is
aaeeiioouu
. - The first iteration the code check the first letter in this string
a
. Because it's ana
is removed from the word. - Now the string is
aeeiioouu
. - 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
2,423 PointsAwesome, thanks for the help!
Matthew Kiggen
2,423 PointsMatthew Kiggen
2,423 PointsBut, if I use "this is a string" as my word it removes all vowels