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

Paul Brubaker
Paul Brubaker
5,258 Points

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)
Paul Brubaker
Paul Brubaker
5,258 Points

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 56,951 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
Paul Brubaker
Paul Brubaker
5,258 Points

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