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

Cameron Simpson cs at zip.com.au
Thu Oct 25 22:15:45 EDT 2012


On 25Oct2012 18:46, mamboknave at gmail.com <mamboknave at gmail.com> wrote:
| >>> a = [float('nan'), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
| >>> a
| [nan, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
| >>> a.index(float('nan'))
| Traceback (most recent call last):
|   File "<stdin>", line 1, in <module>
| ValueError: list.index(x): x not in list
| 
| 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?

The special NaN float value always compares unequal, even to itself.
IEEE floating point FTW!

You're using index incorrectly, but only because it relies on ==
returning True, which it won't.

You can use math.isnan:

  http://docs.python.org/library/math.html#math.isnan
  http://docs.python.org/py3k/library/math.html#math.isnan

for the test instead. Nan requires special handling.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

I'm not making any of this up you know. - Anna Russell



More information about the Python-list mailing list