Python Python Collections Lists Removing items from a list

Vladyslav Koroviakovskyi
Vladyslav Koroviakovskyi
2,729 Points

the condition i used to remove all elements except ints from the list does not remove a list inside the list

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] messy_list.insert(0, messy_list.pop(3))

for item in messy_list: if type(item) != int: messy_list.remove(item)

in the preview, I can see that the output of the function is a list with a list in the end: [1, 2, 3, [1, 2, 3]]

why my condition does not remove a inside list from a list?

lists.py
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))

for item in messy_list:
    if type(item) != int:
        messy_list.remove(item)








# Your code goes below here
Vladyslav Koroviakovskyi
Vladyslav Koroviakovskyi
2,729 Points

ok, i just figured out, I changed the line: for item in messy_list.copy() so, it iterates though a copy, and it worked. can someone explain why i need copy() to make this work, please

1 Answer

Steven Parker
Steven Parker
160,247 Points

Internally, the loop keeps track of which item it is working with by its index. Each time through the loop, the index is incremented and the next item is retrieved.

If you remove an item from the list while the loop is running, the index numbers of the remaining items changes; and that causes the loop to skip the next one in the sequence.

The copy does not change as the loop runs, so every item is checked.