SeasonalShot SeasonalShot - 1 year ago 66
Python Question

Python filter doesn't work as expected

I have the following python code.

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

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:


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download