Python isfinite

The Python isfinite function checks whether the given value is a finite number (Not an Infinity and Not a Number) or not. If it is an infinite number or Not a Number, then isfinite returns False otherwise, True, and its syntax is

math.isfinite(value)

Python isfinite example

In this example, we are using the isfinite function on both positive & negative numeric and decimal values. We have also used Python math.pi as the argument of this Mathematical function.

import math
 
print(math.isfinite(1))
 
print(math.isfinite(0.00))
 
print(math.isfinite(-10))
 
print(math.isfinite(-10.0052))
 
print(math.isfinite(math.pi))
True
True
True
True
True

In this isfinite example, we are passing the infinity and not a number values as the function arguments.

import math
 
print(math.isfinite(0/1))
 
print(math.isfinite(0.00/10))
 
print(math.isfinite(float('NaN')))
 
print(math.isfinite(float('inf')))
 
print(math.isfinite(float('-inf')))
 
print(math.isfinite(math.inf))
 
print(math.isfinite(-math.inf))
Python isfinite Function Example

Does isfinite return true for zero?

Yes. Since zero is a finite number, the built-in math isfinite() function returns true for 0, 0.0, or -0.0.

import math
print(math.isfinite(0))
print(math.isfinite(0.00))
print(math.isfinite(-0.0))
True
True
True

How to check that all values in a list are finite?

When working with lists, there is a possibility that the list may have infinite values (-inf or inf). In such a case, we can use the isfinite function to check whether all values in the given list are finite.

import math
numbers = [10, 20, 0, -15, 14.5]
print(all(math.isfinite(x) for x in numbers))
True

NOTE: If we add one infinite value to a list (float(‘inf’)), the above program will return False as the output. Also, check the isinf() function.

What is the difference between isnan() and isfinite() in Python?

The isnan() function checks whether the given parameter is a NaN (Not a Number). If it is NaN, it returns True. If the argument is a valid number, inf, or -inf, it returns False.

The isfinite() function checks for finite numbers; if the given argument is a finite number, it returns True. If the argument value is NaN, inf, or -inf, it returns False.

In the following example, we use the isnan() and isfinite() functions against 0, infinite, and Not a Number (NaN) values. AS these functions are math library functions, the argument must be a real number. So, use the float() function to convert infinity or nan to a float.

import math
print(math.isfinite(0))
print(math.isnan(0))

print(math.isfinite(float('inf')))
print(math.isnan(float('inf')))

print(math.isfinite(float('nan')))
print(math.isnan(float('nan')))
True
False
False
False
False
True