Python Python Collections Lists Removing items from a list

Why doesn't this code remove the list if its type is 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) print(messy_list)

print(messy_list) returns: [1, 2, 3, [1, 2, 3]]

2 Answers

Steven Parker
Steven Parker
168,518 Points

Altering an iterable inside a loop that it is controlling can cause undesired behavior, such as skipping over items or using them twice.

Always use a copy of an iterable to control a loop if the loop will be making changes to it.

Vincent Cegers
Vincent Cegers
1,248 Points

hey, Steven sorry to bother you again. I am having this same issue even when using a copy could you help me with my code.

messy_list1 = messy_list.copy()

for x in messy_list1:

if type(x) is str or type(x) is bool or type(x) is list:

    messy_list1.remove(x)

print(messy_list1)

Steven Parker
Steven Parker
168,518 Points

Making messy_list1 and using it for the loop was a good idea, but you're also removing items from it. The "remove" needs to be applied to the original "messy_list". :wink:

Steven Parker
Steven Parker
168,518 Points

Ray C — did this answer your question?