What's the difference ?

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Aug 29 16:08:04 CEST 2007


On Wed, 29 Aug 2007 13:39:27 +0000, Alex wrote:

> Hye,
> 
> I was just wondering what is the difference between
> 
>>> if my_key in mydict:
>>>     ...
> 
> and
> 
>>> if mydict.has_keys(my_key):
>>>     ...
> 
> I've search a bit in the python documentation, and the only things I
> found was that they are "equivalent".
> 
> But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/
> Cookbook/Python/Recipe/59875" ), there is difference between the two
> notation.

The comments in this recipes source code are misleading.  Difference is
not the ``in`` but that it is used on ``another_dict.keys()`` in the "bad"
example.  That is a linear search on a list with all keys instead asking
the dictionary directly like you did above.

The difference in your code above is that  ``in`` works on other types too
that implement `__contains__()`, like lists or sets for example, and that
it is a bit faster as the second example has to look up the `has_key()`
method on the object first.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list