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

Rob Bekkering
Rob Bekkering
4,010 Points

Trying to remove vowels but Python/Workspaces keeps skipping a few...

I can't get this code to work.... It keeps missing the 'e' in Faciell and the 'o' in Cleopatra.

my_list = ["Oklahoma", "Jerry", "Faciell", "Gazebo", "Fritzel", "Bonus", "Cleopatra"]
vowels = list("aeuio")

clean_list = []

for word in my_list:
    list_word = list(word.lower())
    for letter in list_word:
        if letter in vowels:
            list_word.remove(letter)
    clean_list.append("".join(list_word).capitalize())

print(clean_list)

I tried a few different approaches but nothing changes. And if i replace the 'o' in Cleopatra with an 'a', it removes the 'a' but leaves the third 'a' at the end.

Rob Bekkering
Rob Bekkering
4,010 Points

And does anybody know how I can display this code properly on the forum??

Steven Parker
Steven Parker
231,269 Points

The instructions for displaying code are in the Markdown Cheatsheet pop-up below the text entry area. :arrow_heading_down:

1 Answer

Steven Parker
Steven Parker
231,269 Points

:point_right: Never alter a list while iterating over it in a loop.

Instead, use a copy of the list for the loop. A slice with no parameters is a convenient way to make a copy:

for letter in list_word[:]:
Rob Bekkering
Rob Bekkering
4,010 Points

Aah! Thank you. It totally worked!!

So if I understand this correctly:

the first for ... in ... : was fine because none of the items were being altered while being looped through. But the second one referenced and altered the list at the same time so it got confused. Which is (I guess) because the index shifts??

Thank you again! This was really helpful!!