How to check the return value of the type() method in Python?

Viewed 223

I'm trying to write a Python 3 function that will filter a list and pop() all items that are a string. But when I try to write the following function:

def filter_list(l):
    for i in l:
        type_item = type(l[i])
        if type_item == "class str":
            l.pop(i)
    return l

I get an error saying:

File "/home/codewarrior/solution.py", line 3, in filter_list
    type_item = type(l[i])
TypeError: list indices must be integers or slices, not str

I believe that the return of this method is not a str, but I haven't found any documentation that tells me how I can check if the return is a string or not. Thank you!

2 Answers

You can accomplish it with a simpler expression using list comprehensions. Check out the following code. It will filter out all strings from your initial list:

start_list = ["test", 1, 2]
filtered_list = [i for i in start_list if type(i) is not str]

Your type_item isn't equal to the following string: "class str"

Instead, you should do that: if type_item is str

Related