(python 2.7.8)
I\'m trying to make a function to extract integers from a mixed list. Mixed list can be anything but the e.g. I\'m going with is:
test
as explained by @pts for isinstance, so use type
like this
[ x for x in testList if type(x)==int ]
output:
[1, 7, 5, 7]
use set
to remove duplication
testList = [1, 4.66, 7, "abc", 5, True, 3.2, False, "Hello", 7]
print([x for x in testList if isinstance(x,int) and not isinstance(x,bool)])
[1, 7, 5, 7]
The best approach is not to use type
, but to use a chain of isinstance
calls. The pitfall of using type
is that someone could subclass int
in the future, and then your code won't work. Also, since you are using Python 2.x, you need to consider numbers greater than or equal to 2^31: these are not ints. You need to consider the long
type:
def parseIntegers(mixedList):
return [x for x in testList if (isinstance(x, int) or isinstance(x, long)) and not isinstance(x, bool)]
Reason for needing to consider long
:
>>> a = 2 ** 31
>>> isinstance(a, int)
False
Apparently bool is a subclass of int:
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(42, int)
True
>>> isinstance(True, int)
True
>>> isinstance('42', int)
False
>>> isinstance(42, bool)
False
>>>
Instead of isinstance(i, int)
, you can use type(i) is int
or isinstance(i, int) and not isinstance(i, bool)
.