a.index(float('nan')) fails

Ethan Furman ethan at stoneleaf.us
Sun Oct 28 09:07:52 EDT 2012


Steven D'Aprano wrote:
> 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.

This is incorrect.  .index() uses identity first, then equality, and 
will match the same NaN in a list.  The OP's problem was in using a 
different NaN.

Having said that, your find_nan() solution is probably the one to use 
anyway.

> 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




More information about the Python-list mailing list