Most languages have a NaN constant you can use to assign a variable the value NaN. Can python do this without using numpy?
Yes  use math.nan
.
>>> from math import nan
>>> print(nan)
nan
>>> print(nan + 2)
nan
>>> nan == nan
False
>>> import math
>>> math.isnan(nan)
True
Before Python 3.5, one could use float("nan")
(case insensitive).
Note that checking to see if two things that are NaN are equal to one another will always return false. This is in part because two things that are "not a number" cannot (strictly speaking) be said to be equal to one another  see What is the rationale for all comparisons returning false for IEEE754 NaN values? for more details and information.
Instead, use math.isnan(...)
if you need to determine if a value is NaN or not.
Furthermore, the exact semantics of the ==
operation on NaN value may cause subtle issues when trying to store NaN inside container types such as list
or dict
(or when using custom container types). See Checking for NaN presence in a container for more details.
You can also construct NaN numbers using Python's decimal module:
>>> from decimal import Decimal
>>> b = Decimal('nan')
>>> print(b)
NaN
>>> print(repr(b))
Decimal('NaN')
>>>
>>> Decimal(float('nan'))
Decimal('NaN')
>>>
>>> import math
>>> math.isnan(b)
True
math.isnan(...)
will also work with Decimal objects.
However, you cannot construct NaN numbers in Python's fractions module:
>>> from fractions import Fraction
>>> Fraction('nan')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\fractions.py", line 146, in __new__
numerator)
ValueError: Invalid literal for Fraction: 'nan'
>>>
>>> Fraction(float('nan'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\fractions.py", line 130, in __new__
value = Fraction.from_float(numerator)
File "C:\Python35\lib\fractions.py", line 214, in from_float
raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
ValueError: Cannot convert nan to Fraction.
Incidentally, you can also do float('Inf')
, Decimal('Inf')
, or math.inf
(3.5+) to assign infinite numbers. (And also see math.isinf(...)
)
However doing Fraction('Inf')
or Fraction(float('inf'))
isn't permitted and will throw an exception, just like NaN.
If you want a quick and easy way to check if a number is neither NaN nor infinite, you can use math.isfinite(...)
as of Python 3.2+.
If you want to do similar checks with complex numbers, the cmath
module contains a similar set of functions and constants as the math
module:
cmath.isnan(...)
cmath.isinf(...)
cmath.isfinite(...)
(Python 3.2+)cmath.nan
(Python 3.6+; equivalent tocomplex(float('nan'), 0.0)
)cmath.nanj
(Python 3.6+; equivalent tocomplex(0.0, float('nan'))
)cmath.inf
(Python 3.6+; equivalent tocomplex(float('inf'), 0.0)
)cmath.infj
(Python 3.6+; equivalent tocomplex(0.0, float('inf'))
)

2Note that using float('nan) is 3x slower than using np.nan, and about 6.5 times slower than assigning nan = float('nan') once and then using the variable 'nan' for all following assignments (as suggested in abarnert's answer). Apr 12 '19 at 17:42
nan = float('nan')
And now you have the constant, nan
.
You can similarly create NaN values for decimal.Decimal.:
dnan = Decimal('nan')

This is the most efficient answer for multiple nan assignments: That is, use float('nan') only once, and then use the assigned constant for all remaining assignments. However if you are only doing one or two assignments of nan total, then using numpy.nan is fastest. Apr 12 '19 at 17:45

You can get NaN from "inf  inf", and you can get "inf" from a number greater than 2e308, so, I generally used:
>>> inf = 9e999
>>> inf
inf
>>> inf  inf
nan

3This answer downvoted unreasonably. I'm writing lots of small parsing tests in .txt files and using ast.literal_eval to get expected output part. It's impossible to call float('nan') there, and this answer was helpful for me. Mar 26 '18 at 15:59

@VitalikVerhovodov Just to point out, since Python 3.7, it is no longer possible to get a NaN value via
ast.literal_eval('1e9991e999')
. See bpo31778 for more details about the change. In the pastast.literal_eval
appears to be able to add and subtract literals, but that was just due to the loose input validation for supporting evaluation of complex number literals. According to its official documentation,ast.literal_eval
is not designed for evaluating expressions involving operators. Jun 22 at 6:35
A more consistent (and less opaque) way to generate inf and inf is to again use float():
>> positive_inf = float('inf')
>> positive_inf
inf
>> negative_inf = float('inf')
>> negative_inf
inf
Note that the size of a float varies depending on the architecture, so it probably best to avoid using magic numbers like 9e999, even if that is likely to work.
import sys
sys.float_info
sys.float_info(max=1.7976931348623157e+308,
max_exp=1024, max_10_exp=308,
min=2.2250738585072014e308, min_exp=1021,
min_10_exp=307, dig=15, mant_dig=53,
epsilon=2.220446049250313e16, radix=2, rounds=1)
NAN
; it's a constant defined inmath.h
, as of C99. (I feel it's fair to call the most recent standardized version of the language as that language. Thus "C" is C11.) (see stackoverflow.com/questions/1923837/howtousenanandinfinc); in C++, it'sNAN
as well, there's alsonan()
,nanf()
, andnanl()
, though I'm a bit less certain as to what they do.double.NaN
in Java,Double.NaN
in C#…