I have a list:
['Jack', 18, 'IM-101', 99.9]
How do I filter it to get only the integers from it??
I tried
map(int, x)
but it gives error.
ValueError: invalid literal for int()
with base 10: 'Jack'
To filter a list in Python, use the built-in filter() function.
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. syntax: filter(function, sequence) Parameters: function: function that tests if each element of a sequence true or not.
Use filter
:
filter(lambda e: isinstance(e, int), x)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With