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 does my if loop not remove the list of numbers inside messy_list?

I thought that using "if type(item) is not int" would remove the list of numbers within messy_list.

I tried testing type([1, 2, 3]) in the REPL and it tells me that the class is 'list'.

I don't see why my loop would not remove the list then. Can anyone help me with 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))

# Loop through each item in messy_list
for item in messy_list:
    if type(item) is not int:
        messy_list.remove(item)

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

It is because you are modifying the same list you are iterating over. When you do a remove, you change that list index and the next time through the loop it will skip an entry.

First time through the list your index is 0 and you check the letter "a". Then you remove the letter a. Next time through the list you inspect index 1 which is now 3 (not 2 as expected - which isn't really noticed since 2 doesn't get removed anyway). Now when you get to False and remove it, you'll skip that final nested list.

You need to loop a copy of the list.

Thank you for the help!