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?

Asked By: Craig Messina

||

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]
Answered By: ThePyGuy

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

Answered By: Lior Tabachnik

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.

Answered By: Buzz

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.

Answered By: Bot
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.