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

Alex Rosier
PRO
Alex Rosier
Pro Student 648 Points

I am using the type() function to identify data types in list and remove by type. Why does this fail for inner list?

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

Your code goes below here

messy_list.insert(0, messy_list.pop(3))

for item in messy_list: if type(item) is str: messy_list.remove(item) elif type(item) is bool: messy_list.remove(item) # Why does the below fail to execute? elif type(item) is list: messy_list.remove(item) else: pass

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 item in messy_list: 
    if type(item) is str:
        messy_list.remove(item)
    elif type(item) is bool:
        messy_list.remove(item)
    # Why does the below fail to execute?
    elif type(item) is list:
        messy_list.remove(item)
    else: 
        pass

1 Answer

Steven Parker
Steven Parker
172,267 Points

Removing items from an iterable while it is controlling a loop can cause other items to be skipped. To avoid this, you can use a copy of the iterable to control the loop.

Also, you can simplify things by removing anything that's not what you want instead of each explicit other type:

for item in messy_list.copy(): 
    if type(item) is not int:
        messy_list.remove(item)