List comprehension is a powerful tool for working with lists. It allows you to easily get integer values from a list, without having to write multiple lines of code. In this article, we'll show you how to use list comprehension to get integer values from a list.
my_list = ["a", 1, "b", 2, 3, 4, "c", "d"]
result = [val for val in my_list if isinstance(val, (int, float))]
print(result)
Output
[1, 2, 3, 4]
You can also import the numbers module and use them in instance() function. Check the below example.
import numbers
my_list = ["a", 1, "b", 2, 3, 4, "c", "d"]
result = [val for val in my_list if isinstance(val, numbers.Number)]
print(result)
Output
[1, 2, 3, 4]
The above code example is using a list comprehension to create a new list. The new list will contain all of the values from the original list that are instances of the numbers.Number class.
Python's built-in isdigit() function can be used to check if a string is an integer. This function is used in conjunction with a list comprehension to get a list of all integers in a given list.
In the below code example we have all values in string format and we want to extract the number values from it.
my_list = ["a", "1", "b", "2", "3", "4", "c", "d"]
result = [val for val in my_list if val.isdigit()]
print(result)
Output
['1', '2', '3', '4']
Walkthrough:
0 Comments