checking if an object IS in a list

Peter Otten __peter__ at web.de
Fri Jul 18 11:30:09 CEST 2008


nicolas.pourcelot at gmail.com wrote:

> 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...

There is no "is in" operator in Python, but you can write your test more
concisely as

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
> ...
>>>> 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 ?

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).

Peter



More information about the Python-list mailing list