python

Get integer only values from a list in Python

If you have a list in Python that contains both integer and non-integer values, and you want to create a new list that contains only the integer values, there are a few ways you can do this. One way is to use a list comprehension, which is a powerful tool for creating lists based on other lists. Another way is to use the built-in function isinstance(), which allows you to check if a value is an integer.

Get integer values from a list using isinstance() function and list comprehension

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]
  1. The code creates a list called my_list with a mix of strings and integers.
  2. It then iterates through each value in my_list using a For loop.
  3. For each value, it checks if the value is an instance of either the int or float class.
  4. If the value is an instance of either int or float, it is added to a new list called result.
  5. Finally, the code prints out the contents of the result.

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.

Get integer values from a list using isdigit() function and list comprehension (If all values are in string format)

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:

  1. The code creates a list called my_list.
  2. The code then creates a new list called result.
  3. The code looks through each value in my_list and sees if it is a digit.
  4. If the value is a digit, it is added to the result list.
  5. The code then prints the result list.
Was this helpful?