+5 votes
in Programming Languages by (51.1k points)
In a list, some values are integers, and some are characters. I want to check if the value is numeric before using it. How to check if the value is numeric?

1 Answer

+1 vote
by (157k points)

isinstance() can be used to check if a given value is numeric or not.

Here is an example to test the elements of a list:

aa = [3, 4, "6", "8", 9]
for v in aa:
    if isinstance(v, (int, float)):
        print("Value {0} is numeric".format(v))
        print("Value {0} is not numeric".format(v))

The above code will print the following:

Value 3 is numeric
Value 4 is numeric
Value 6 is not numeric
Value 8 is not numeric
Value 9 is numeric