How can I select only integers from list and not booleans?
Question:
I have a code to get only integers from a list:
list = [i for i in list if isinstance(i, int)]
However, if the list is [True, 19, 19.5, False]
, it will return [True, 19, False].
I need it to return only [19]
, not the True
and False
. How do I do that?
Answers:
As mentioned in the comment, True/False
values are also the instances of int
in Python, so you can add one more condition to check if the value is not an instance of bool
:
>>> lst = [True, 19, 19.5, False]
>>> [x for x in lst if isinstance(x, int) and not isinstance(x, bool)]
[19]
bool
is a subclass of int
, therefore True
is an instance of int
.
False
equal to 0
True
equal to 1
you can use another check or if type(i) is int
Use type
comparison instead:
_list = [i for i in _list if type(i) is int]
Side note: avoid using list
as the variable name since it’s the Python builtin name for the list
type.
You could try using a conditional statement within your code that checks for isinstance(i, int) and only appends i to the list if that condition is True.
I have a code to get only integers from a list:
list = [i for i in list if isinstance(i, int)]
However, if the list is [True, 19, 19.5, False]
, it will return [True, 19, False].
I need it to return only [19]
, not the True
and False
. How do I do that?
As mentioned in the comment, True/False
values are also the instances of int
in Python, so you can add one more condition to check if the value is not an instance of bool
:
>>> lst = [True, 19, 19.5, False]
>>> [x for x in lst if isinstance(x, int) and not isinstance(x, bool)]
[19]
bool
is a subclass of int
, therefore True
is an instance of int
.
False
equal to0
True
equal to1
you can use another check or if type(i) is int
Use type
comparison instead:
_list = [i for i in _list if type(i) is int]
Side note: avoid using list
as the variable name since it’s the Python builtin name for the list
type.
You could try using a conditional statement within your code that checks for isinstance(i, int) and only appends i to the list if that condition is True.