What's the difference ?
aleax at mac.com
Wed Aug 29 16:44:56 CEST 2007
Alex <alexandre.badez at gmail.com> wrote:
> I was just wondering what is the difference between
> >> if my_key in mydict:
> >> ...
> >> if mydict.has_keys(my_key):
Mis-spelled (no final s in the method name).
> >> ...
> I've search a bit in the python documentation, and the only things I
> found was that they are "equivalent".
Semantically they are, but `in' is faster, more concise, & readable.
> But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/
> Cookbook/Python/Recipe/59875" ), there is difference between the two
What that example is pointing to as "wrong way" is a NON-equivalent
approach that's extremely slow:
if my_key in mydict.keys():
The call to keys() takes time and memory to build a list of all keys,
after which the ``in'' operator, having a list as the RHS operand, is
also quite slow (O(N), vs O(1)!). So, never use that useless and silly
call to keys() in this context!
More information about the Python-list