a.index(float('nan')) fails
Terry Reedy
tjreedy at udel.edu
Fri Oct 26 04:00:03 EDT 2012
On 10/25/2012 10:19 PM, MRAB wrote:
> On 2012-10-26 03:04, Terry Reedy wrote:
>> On 10/25/2012 9:46 PM, 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'))
This is a second nan object, and it is not in the list.
>>> 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?
>>
>> It is a consequence of the following, which some people (but not all)
>> believe is mandated by the IEEE standard.
>>
>> >>> nan = float('nan')
>> >>> nan is nan
>> True
>> >>> nan == nan
>> False
>>
>> >>> nanlist = [nan]
>> >>> nan in nanlist
>> True
>> >>> nanlist.index(nan)
>> 0
.index found the nan.
>> Containment of nan in collection is tested by is, not ==.
>>
>> >>> nan2 = float('nan')
>> >>> nan2 is nan
>> False
>> >>> nan2 == nan
>> False
>> >>> nan2 in nanlist
>> False
>>
> In summary, .index() looks for an item which is equal to its argument,
> but it's a feature of NaN (as defined by the standard) that it doesn't
> equal NaN, therefore .index() will never find it.
Except that is *does* find the particular nan object that is in the
collection. So nan in collection and list.index(nan) look for the nan by
identity, not equality. This inconsistency is an intentional decision to
not propagate the insanity of nan != nan to Python collections.
--
Terry Jan Reedy
More information about the Python-list
mailing list