Filter a list in python get integers

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'

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

>>> x = ['Jack', 18, 'IM-101', 99.9]
>>> [e for e in x if isinstance(e, int)]
[18]

Method 2

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.

Method 3

Use filter:

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

Method 4

Use list comprehension

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

map(int, x) throws an error

map function applies int(t) on every element of x.

This throws an error because int(‘Jack’) will throw an error.
[Edit:]
Also isinstance is purer way of checking that it is of type integer, as sukhbir says.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x