Common Python Idioms
Stephen Eilert
spedrosa at gmail.com
Thu Dec 7 07:08:18 EST 2006
Hendrik van Rooyen escreveu:
> <skip at pobox.com> wrote:
>
> > Peter> Bjoern Schliessmann wrote:
> > >> Wouldn't be "if k in d.keys()" be the exact replacement?
> >
> > Peter> No, 'k in d' is equivalent to 'd.has_key(k)', only with less
> > Peter> (constant) overhead for the function call. 'k in d.keys()' on the
> > Peter> other hand creates a list of keys which is then searched linearly
> > Peter> -- about the worst thing you can do about both speed and memory
> > Peter> footprint.
I've always used has_key(), thinking it was the only way to do it.
Given that Python says that "There Should Be Only One Way to Do It", I
didn't bother searching for alternatives.
Is there a list somewhere listing those not-so-obvious-idioms? I've
seen some in this thread (like the replacement for .startswith).
I do think that, if it is faster, Python should translate
"x.has_key(y)" to "y in x".
Stephen
More information about the Python-list
mailing list