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

Nobody nobody at nowhere.com
Sat Oct 27 12:40:19 EDT 2012


On Thu, 25 Oct 2012 22:04:52 -0400, Terry Reedy wrote:

> Containment of nan in collection is tested by is, not ==.

AFAICT, it isn't specific to NaN. The test used by .index() and "in"
appears to be equivalent to:

	def equal(a, b):
	    return a is b or a == b

IOW, it always checks for object identity before equality.

Replacing NaN with an instance of a user-defined class with a
non-reflexive __eq__() method supports this:

	> class Foo(object):
	=  def __eq__(self, other):
	=   return False
	= 
	> a = Foo()
	> b = Foo()
	> a in [1,2,a,3,4]
	True
	> b in [1,2,a,3,4]
	False
	> [1,2,a,3,4].index(a)
	2
	> [1,2,a,3,4].index(b)
	Traceback (most recent call last):
	  File "<stdin>", line 1, in <module>
	ValueError: <__main__.Foo object at 0x7fa7055b0550> is not in list





More information about the Python-list mailing list