1

I know I can get nan in Python by

>>>float("nan")
nan

But is there any other way of getting it without "nan"? Like in Javascript, I can do

>"something"-1
NaN

Can I do something simillar in Python? Thanks.

Adam Ježek
  • 464
  • 5
  • 15
  • you will get `TypeError`, `nan` can be obtained by dividing infinities (e. g. `float('inf)` and `-float('inf)`) – Azat Ibrakov Apr 26 '17 at 15:42
  • If you have access to NumPy, you could do `np.int16(1)/0 - np.int16(1)/0` or merely use `numpy.nan`, but that's less fun, isn't it? – ForceBru Apr 26 '17 at 15:50
  • [*"There should be one-- and preferably only one --obvious way to do it."*](https://www.python.org/dev/peps/pep-0020/) Why do you need *another* way to get NaN? – jonrsharpe Apr 26 '17 at 16:08

1 Answers1

7

If you are using Python 3.5 or later, NaN is available as the constant math.nan:

import math
print(math.nan) # nan

In earlier versions, you can get NaN only by casting it from string:

print(float('NaN')) # nan

Or by trying to do weird operations on infinity:

print(float('Inf') - float('Inf')) # nan

You can also use the numpy library. However, numpy is a big library and you shouldn't use it just for this.

import numpy as np
print(np.nan) # nan
Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39
  • 3
    `numpy` is a big library, but you could of course just import nan by itself. `from numpy import nan`. – zephyr Apr 26 '17 at 15:49
  • @zephyr I think what they meant is that you shouldn't install the whole package only to get nan. But I agree, if it's already available then importing nan alone is the best solution. – km6 Aug 10 '18 at 09:14