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 Removing items from a list

Why is the list not removed the first time, but is removed the second time when I test this code?

I thought this code should work, so I tested it outside of the challenge window. When I run the code the first time, it removes the character and the boolean, as expected, but leaves the list. When I run the code again on the new messy_list that has the boolean and the character already removed, it does remove the list. I don't understand what causes this.

lists.py
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

# Your code goes below here
messy_list.insert(0,messy_list.pop(3))
for element in messy_list:
    if type(element) is not int:
        messy_list.remove(element)

I also tried having the program print the output of type(element) as it iterates through the list, and the output was as expected, string, int, int, int, bool, list.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

You are modifying the list you are iterating over: messy_list

This causes the for loop to skip items. Adding a print shows the skipping.

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
# Your code goes below here
messy_list.insert(0,messy_list.pop(3))
for element in messy_list:
    print(element)
    if type(element) is not int:
        messy_list.remove(element)

# print returns
1
a
3
False

The quick fix is to use:

for element in messy_list.copy():
```Python

Awww, now I feel silly. I should have caught that one, thank you Chris Freeman!