How to Get Only Numbers from a List in Python?
Hey,
I am going to show you an example of get integer only values from a list in python. This article goes in detailed on python get only numbers from list. I am going to show you about how to get only integer value from list in python. This article goes in detailed on how to get only numbers from a list in python. Alright, let us dive into the details.
If you have list in python with numeric and non-numeric values in list and you want to get only numeric values from list in python, then there are several ways to do that. i will give you simple two examples here using comprehension with isinstance() and isdigit() functions. so, let's see the following examples:
You can use these examples with python3 (Python 3) version.
let's see below a simple example with output:
Example 1:
main.py
# Create New List with Item myList = ["a", 1, 2, "b", "c", 4, 5, "d"] # Get integer only values from a list in Python newList = [val for val in myList if isinstance(val, (int, float))] print(newList)
Output:
[1, 2, 3, 4, 5]
Example 2:
main.py
# Create New List with Item myList = ["a", "1", "2", "b", "c", "4", "5", "d"] # Get integer only values from a list in Python newList = [val for val in myList if val.isdigit()] print(newList)
Output:
['1', '2', '3', '4', '5']
I hope it can help you...