Filter a list in python get integers
In case the list contains integers that are formatted as str
, the isinstance()
solutions would not work.
['Jack', '18', 'IM-101', '99.9']
I figured out the following alternative solution for that case:
list_of_numbers = []
for el in your_list:
try:
list_of_numbers.append(int(el))
except ValueError:
pass
You can find more details about this solution in this post, containing a similar question.
>>> x = ['Jack', 18, 'IM-101', 99.9]
>>> [e for e in x if isinstance(e, int)]
[18]