SeasonalShot SeasonalShot - 5 months ago 7
Python Question

Python filter doesn't work as expected

I have the following python code.

a =[1,2,3,'4','55',6]
filter(int,a)


The output is :

[1, 2, 3, '4', '55', 6]


Filter is supposed to remove the elements from the provided sequence which translates into false, and return only those elements which translates into true.

I expected the output to be:

[1,2,3,6]


since these are the only int in my list.
Am i missing something essential ?

Answer

Use isinstance instead:

>>> a =[1,2,3,'4','55',6]
>>> filter(lambda x: isinstance(x, int),a)
[1, 2, 3, 6]

int will convert each object to integer and since all numbers/strings on the list are non-zero filter picks them all since they evaluate True in boolean context. Instead of that it seems that your goal is to pick objects that are already ints and that can be done with isinstance.