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

Shane Smith
Shane Smith
2,726 Points

How do i remove different types from a list?

cant seem to get this to work...

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))
test_list = messy_list.copy()
for item in test_list:
    if item == list or item == str or item == bool:
        messy_list.remove(item)

2 Answers

Steven Parker
Steven Parker
172,328 Points

You're close, but instead of comparing the item itself, you'll want to compare the type of the item:

    if type(item) == list or type(item) == str or type(item) == bool:

Optionally, you could make the test more compact by looking for everything with a type other than what you want to keep:

    if type(item) != int: