Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I select only integers from list and not booleans?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading