checking if an object IS in a list

Peter Otten __peter__ at
Fri Jul 18 12:26:44 CEST 2008

nicolas.pourcelot at wrote:

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

And rarely used. Probably even less than the (also missing)

< in, | in, you-name-it 


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

Correct for set, dict. For lists etc. the hash doesn't matter:

>>> class A(object):
...     def __hash__(self):
...             return nexthash()
...     def __eq__(self, other):
...             return True
>>> from itertools import count
>>> nexthash = count().next
>>> A() in [A() for _ in range(3)]
>>> d = dict.fromkeys([A() for a in range(3)])
>>> d.keys()[0] in d


More information about the Python-list mailing list