checking if an object IS in a list

nicolas.pourcelot at gmail.com nicolas.pourcelot at gmail.com
Fri Jul 18 12:03:53 CEST 2008


On 18 juil, 11:30, Peter Otten <__pete... at web.de> wrote:
> nicolas.pource... 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)
>
>
>

Thanks a lot
However, any() is only available if python version is >= 2.5, but I
may define a any() function on initialisation, if python version < 2.5

I think something like
>>> id(myobject) in (id(element) for element in mylist)
would also work, also it's not so readable, and maybe not so fast
(?)...

An "is in" operator would be nice...

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

So, precisely, you mean that if hash(a) != hash(b), a and b are
considered distinct, and else [ie. if hash(a) == hash(b)], a and b are
the same if and only if a == b ?



More information about the Python-list mailing list