Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check if list items are integers? [duplicate]

I have a list which contains numbers and letters in string format.

mylist=['1','orange','2','3','4','apple'] 

I need to come up with a new list which only contains numbers:

mynewlist=['1','2','3','4'] 

If I have a way to check if each item in list can be converted to Integer, I should be able to come up with what I want by doing something like this:

for item in mylist:     if (check item can be converted to integer):         mynewlist.append(item) 

How do I check that a string can be converted to an integer? Or is there any better way to do it?

like image 281
Chris Aung Avatar asked Jun 04 '13 00:06

Chris Aung


People also ask

How do you check if an element in a list is an integer in Python?

A list of integers is defined and is displayed on the console. The 'all' operator is used to check if every element is a digit or not. This is done using the 'isdigit' method. The result of this operation is assigned to a variable.

Does list contain duplicates Python?

Python list can contain duplicate elements.

Does list contain duplicate values?

As we know that list can hold duplicate values but will not update if it contains duplicate values. I tried to convert the list to Set or Map to hold unique values but the problem is we cannot perform DML operation on Set ot Map.


1 Answers

Try this:

mynewlist = [s for s in mylist if s.isdigit()] 

From the docs:

str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.


As noted in the comments, isdigit() returning True does not necessarily indicate that the string can be parsed as an int via the int() function, and it returning False does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.

like image 163
arshajii Avatar answered Sep 22 '22 04:09

arshajii