+5 votes
in Programming Languages by (74.2k 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

+2 votes
by (349k points)
selected by
 
Best answer

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))
    else:
        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


...