Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,082 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!