Python Python Collections (2016, retired 2019) Lists Removing items from a list

ps18
ps18
2,027 Points

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,780 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.

ps18
ps18
2,027 Points

Thank you for the help!