Filter list in python get integers

I have a list:

['Jack', 18, 'IM-101', 99.9] 

How to filter it to get only integers from it?

I tried

 map(int, x) 

but he gives an error.

 ValueError: invalid literal for int() with base 10: 'Jack' 
+4
source share
4 answers
 >>> x = ['Jack', 18, 'IM-101', 99.9] >>> [e for e in x if isinstance(e, int)] [18] 
+12
source

Use list.

 >>> t = ['Jack', 18, 'IM-101', 99.9] >>> [x for x in t if type(x) == type(1)] [18] >>> 

map (int, x) throws an error

The map function applies int (t) to each x element.

This causes an error because int ('Jack') will throw an error.

[Edit:]

Also, isinstance is a cleaner way of checking that it is of type integer, as the suhbir says.

+2
source

If the list contains integers formatted as str , understanding the list will not work.

 ['Jack', '18', 'IM-101', '99.9'] 

I figured out the following alternative solution for this case:

 list_of_numbers = [] for el in your_list: try: list_of_numbers.append(int(el)) except ValueError: pass 

More details about this solution can be found in this post , which contains a similar question.

+1
source

Use filter :

 filter(lambda e: isinstance(e, int), x) 
0
source

All Articles