checking if an object IS in a list
__peter__ at web.de
Fri Jul 18 11:30:09 CEST 2008
nicolas.pourcelot at gmail.com wrote:
> I want to test if an object IS in a list (identity and not equality
> I can if course write something like this :
> test = False
> myobject = MyCustomClass(*args, **kw)
> for element in mylist:
> if element is myobject:
> test = True
> 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...
There is no "is in" operator in Python, but you can write your test more
any(myobject is element for element in mylist)
> 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
>>>> b in set([a])
> set([<__main__.A object at 0xb7a91dac>])
> So there is some equality check also, maybe only if '__eq__' is
> implemented ?
In general equality is determined by __eq__() or __cmp__(). By default
object equality checks for identity.
Some containers (like the built-in set and dict) assume that a==b implies
hash(a) == hash(b).
More information about the Python-list