math.isfinite(x) returns True if x is a finite number—neither positive/negative infinity nor NaN—and False otherwise.
Added in Python 3.2, it gives a single-call guard before saving JSON, computing averages, or rejecting corrupted inf and nan sensor readings.
math.isfinite() is a function in Python's standard math module: import it with import math and call math.isfinite(...), or import the name directly with from math import isfinite.
Syntax
Import math and pass a numeric value.
python
import math
valid = math.isfinite(x)
Call
What it does
math.isfinite(42.5)
Returns True.
math.isfinite(0.0)
Returns True (zero is finite).
math.isfinite(float("inf"))
Returns False.
math.isfinite(float("nan"))
Returns False.
Notice math.isfinite(x) is identical to not (math.isinf(x) or math.isnan(x)) and also returns True for subnormal numbers and -0.0.
Function signatures
python
math.isfinite(x, /)
# added in Python 3.2; returns bool
Parameters
Parameter
Description
x
Required positional number (int or float).
Return Value
Return Value
Description
bool
True if x is finite, False if inf, -inf, or nan.
Python Examples
Example 1 — Keep Only Valid Finite Numbers in a Telemetry List
Strip out inf, -inf, and nan values before computing a clean math.fsum() average.
python
import math
readings = [12.5, float("inf"), 0.0, float("nan"), -4.0, float("-inf")]
clean = [x for x in readings if math.isfinite(x)]
print("clean:", clean)
print("mean :", math.fsum(clean) / len(clean))
Output
clean: [12.5, 0.0, -4.0]
mean : 2.8333333333333335
How It Works
Single-predicate cleanup. Filtering with math.isfinite(x) rejects both infinities and NaN in one step.
Zero stays valid. Normal 0.0 and negative -4.0 remain in the cleaned list.
Safe downstream math. Averaging with math.fsum() no longer gets poisoned into nan or inf.
Example 2 — Check Regular Integers vs OverflowError on Huge Ints
See math.isfinite() succeed on normal ints and subnormals while rejecting 10 ** 400.
python
import math
print(math.isfinite(0), math.isfinite(-0.0), math.isfinite(1e-310))
try:
math.isfinite(10 ** 400)
except OverflowError:
print("huge int exceeds float conversion limit")
Output
True True True
huge int exceeds float conversion limit
How It Works
Zero and subnormals are finite. Both -0.0 and tiny subnormal 1e-310 return True.
Float conversion happens first. Converting a 401-digit integer to float raises OverflowError before checking finiteness.
Guard mixed int/float inputs. Use isinstance(x, int) or math.isfinite(x) when arbitrary-size ints might appear.
Example 3 — Print a Truth Table Comparing isfinite, isinf, and isnan
Confirm that finite, infinite, and NaN categories partition all floats cleanly.
python
import math
samples = [1.5, 0.0, float("inf"), float("-inf"), float("nan")]
for v in samples:
fin, inf, nan = math.isfinite(v), math.isinf(v), math.isnan(v)
print(f"{v:>4} | finite={str(fin):>5} inf={str(inf):>5} nan={str(nan):>5}")