Check if list contains only numbers python

In this tutorial, we will look at how to check if a list contains only numbers in Python with the help of some examples.

How to check if all list elements are numbers?

You can use a combination of the Python built-in isinstance[] and all[] function to check if a list contains only numbers. For instance, you can use the following steps to check if all elements in a list are integers in Python –

  1. In a list comprehension, for each element in the list, check if it’s an integer using the isinstance[] function.
  2. Apply the Python built-in all[] function to return True only if all the items in the above list comprehension correspond to True.

The following is the code to check if all elements in a list are integers or not.

# check if all elements in ls are integers
all[[isinstance[item, int] for item in ls]]

Let’s take a look at an example.

# list of numbers
ls = [1, 2, 3, 4]
# check if list contains only numbers
print[all[[isinstance[item, int] for item in ls]]]

Output:

True

We get True as the output as all elements in the list ls are integers.

Let’s take a look at another example.

# list of numbers and a string
ls = [1, 2, 3, 4, 'cat']
# check if list contains only numbers
print[all[[isinstance[item, int] for item in ls]]]

Output:

False

Here we get False as the output because not all elements in the list ls are integers. One element, “cat” in the list is a string.

Check if all items in a list of strings are numeric

If you, however, have a list of strings and want to check whether all the elements in the list are digits or not, you can use the following code.

# list of numeric strings
ls = ["1", "2", "3", "4"]
# check if list of string contains only numberic elements
print[all[[item.isdigit[] for item in ls]]]

Output:

True

Here we check whether each element in the list of strings, ls is a numerical value or not using the string isdigit[] function. We get True as the output as all the strings in the list ls are numeric characters.

You might also be interested in –

  • Python – Check if String Contains Only Numbers
  • Python – Check List Contains All Elements Of Another List


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

The usual way to check whether something can be converted to an int is to try it and see, following the EAFP principle:

try:
    int_value = int[string_value]
except ValueError:
    # it wasn't an int, do something appropriate
else:
    # it was an int, do something appropriate

So, in your case:

for item in mylist:
    try:
        int_value = int[item]
    except ValueError:
        pass
    else:
        mynewlist.append[item] # or append[int_value] if you want numbers

In most cases, a loop around some trivial code that ends with mynewlist.append[item] can be turned into a list comprehension, generator expression, or call to map or filter. But here, you can't, because there's no way to put a try/except into an expression.

But if you wrap it up in a function, you can:

def raises[func, *args, **kw]:
    try:
        func[*args, **kw]
    except:
        return True
    else:
        return False

mynewlist = [item for item in mylist if not raises[int, item]]

… or, if you prefer:

mynewlist = filter[partial[raises, int], item]

It's cleaner to use it this way:

def raises[exception_types, func, *args, **kw]:
    try:
        func[*args, **kw]
    except exception_types:
        return True
    else:
        return False

This way, you can pass it the exception [or tuple of exceptions] you're expecting, and those will return True, but if any unexpected exceptions are raised, they'll propagate out. So:

mynewlist = [item for item in mylist if not raises[ValueError, int, item]]

… will do what you want, but:

mynewlist = [item for item in mylist if not raises[ValueError, item, int]]

… will raise a TypeError, as it should.

How do you check if a list contains only numbers in Python?

Check If a List Contains Only Numbers in Python.
In a list comprehension, for each element in the list, check if it's an integer using the isinstance[] function..
Apply the Python built-in all[] function to return True only if all the items in the above list comprehension correspond to True ..

How do you find numbers in a list Python?

To find an element in the list, use the Python list index[] method, The index[] is an inbuilt Python method that searches for an item in the list and returns its index. The index[] method finds the given element in the list and returns its position.

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

To check if the variable is an integer in Python, we will use isinstance[] which will return a boolean value whether a variable is of type integer or not. After writing the above code [python check if the variable is an integer], Ones you will print ” isinstance[] “ then the output will appear as a “ True ”.

Can a list contain an integer as an element?

As you would expect, we can also assign list values to variables and pass lists as parameters to functions. A list can contain only integer items.

Chủ Đề