How to check if a python variable is a number (integer, float) ?


Examples of how to check if a python variable is a number (integer, float):

Check if a python variable is a number using isinstance

To check if a python variable is a number (int or float par example), a solution is to use isinstance:

x = 1.2

isinstance(x, (int, float))

returns here

True

while

x = 'abcd'

isinstance(x, (int, float))

returns

 false

Case of a string variable

In the case of a string variable

x = '1'

the function isinstance

isinstance(x, (int, float))

will return

False

but to test if a string represents a number, a solution is to use isdigit, example

x = '1'

x.isdigit()

returns

True

Filter a list to keep only numbers

Example of application, let's consider the following list:

l = [5, 3, 2, 'a', 9, 1, 4, 'NaN']

that can be filtered to keep only the numbers

que l'on peut filtrer pour ne garder que les nombres:

l = [i for i in l if isinstance(i, (int, float))]

print(l)

returns

[5, 3, 2, 9, 1, 4]

References