Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a list in python get integers

Tags:

python

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'
like image 627
James I Avatar asked Dec 05 '10 07:12

James I


People also ask

How do you filter numbers in a list in Python?

To filter a list in Python, use the built-in filter() function.

How do you filter elements in Python?

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.


2 Answers

Use filter:

filter(lambda e: isinstance(e, int), x)
like image 93
Nikolay Makhalin Avatar answered Oct 23 '22 08:10

Nikolay Makhalin


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.

like image 42
J0ANMM Avatar answered Oct 23 '22 08:10

J0ANMM