checking if an object IS in a list
nicolas.pourcelot at gmail.com
nicolas.pourcelot at gmail.com
Fri Jul 18 05:09:57 EDT 2008
Hi,
I want to test if an object IS in a list (identity and not equality
test).
I can if course write something like this :
test = False
myobject = MyCustomClass(*args, **kw)
for element in mylist:
if element is myobject:
test = True
break
and I can even write a isinlist(elt, mylist) function.
But most of the time, when I need some basic feature in python, I
discover later it is in fact already implemented. ;-)
So, is there already something like that in python ?
I tried to write :
'element is in mylist'
but this appeared to be incorrect syntax...
All objects involved all have an '__eq__' method.
Thanks,
N. P.
PS: Btw, how is set element comparison implemented ? My first
impression was that 'a' and 'b' members are considered equal if and
only if hash(a) == hash(b), but I was obviously wrong :
>>> class A(object):
... def __eq__(self,y):
... return False
... def __hash__(self):
... return 5
...
>>> a=A();b=A()
>>> a==b
False
>>> hash(b)==hash(a)
True
>>> b in set([a])
False
>>> S=set([a])
>>> S.difference([b])
set([<__main__.A object at 0xb7a91dac>])
So there is some equality check also, maybe only if '__eq__' is
implemented ?
More information about the Python-list
mailing list