1

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • In python `True` is `1` and `False` is `0`. `bool` is subclass of `int`. To check if value is just `int` you need to use either `type(i) is int` or add second condition `not isinstance(i, bool)` – Olvin Roght Oct 15 '22 at 16:42
  • @Olvin That might be a confusing way to put it since `True is not 1 and False is not 0`. It'd be clearer to just say that `bool` is a subclass of `int` and `True == 1 and False == 0`. – wjandrea Oct 15 '22 at 16:45
  • 2
    Also, best not to name variables `list` as that's a built-in type. – sj95126 Oct 15 '22 at 16:45
  • @wjandrea, but `hash(True) == hash(1)` – Olvin Roght Oct 15 '22 at 16:46
  • @Olvin So? `hash(1.0) == hash(1)` – wjandrea Oct 15 '22 at 16:46
  • Related: [What's the canonical way to check for type in Python?](/q/152580/4518341) (covers `isinstance(x, )` vs `type(x) is `) – wjandrea Oct 15 '22 at 17:01
  • Does this answer your question? [python how to distinguish bool from int](https://stackoverflow.com/questions/48025345/python-how-to-distinguish-bool-from-int) – mkrieger1 Oct 15 '22 at 21:57

3 Answers3

4

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Buzz
  • 1,102
  • 1
  • 9
  • 24
2

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]
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
0

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