a.index(float('nan')) fails
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Oct 25 22:33:06 EDT 2012
On Thu, 25 Oct 2012 18:46:20 -0700, mamboknave wrote:
> That means, the function .index() cannot detect nan values. It happens
> on both Python 2.6 and Python 3.1
>
> Is this a bug? Or I am not using .index() correctly?
You shouldn't be using index() or == to detect NANs. The right way to
detect NANs is with the math.isnan() function.
The list.index method tests for the item with equality. Since NANs are
mandated to compare unequal to anything, including themselves, index
cannot match them.
Try this instead:
from math import isnan
def find_nan(seq):
"""Return the index of the first NAN in seq, otherwise None."""
for i, x in enumerate(seq):
if isnan(x):
return i
For old versions of Python that don't provide an isnan function, you can
do this:
def isnan(x):
return x != x
--
Steven
More information about the Python-list
mailing list