Re: Should I use "if" or "try" (as a matter of speed)?
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Should I use "if" or "try" (as a matter of speed)?

From: Aahz <aahz@pythoncraft.com>
Date: Sun Jul 10 2005 - 15:21:02 CEST

Roy, I know you actually know this stuff, but for the benefit of
beginners....

In article <roy-044F62.15060709072005@reader2.panix.com>,
Roy Smith <roy@panix.com> wrote:
>
>3) In some cases, they can lead to faster code. A classic example is
>counting occurances of items using a dictionary:
>
> count = {}
> for key in whatever:
> try:
> count[key] += 1
> except KeyError:
> count[key] = 1
>
>compared to
>
> count = {}
> for key in whatever:
> if count.hasKey(key):
> count[key] += 1
> else:
> count[key] = 1

Except that few would write the second loop that way these days::

    for key in whatever:
        if key in count:
            ...

Using ``in`` saves a bytecode of method lookup on ``has_key()`` (which is
the correct spelling). Or you could choose the slightly more convoluted
approach to save a line::

    for key in whatever:
        count[key] = count.get(key, 0) + 1

If whatever had ``(key, value)`` pairs, you'd do::

    key_dict = {}
    for key, value in whatever:
        key_dict.setdefault(key, []).append(value)

-- 
Aahz (aahz@pythoncraft.com)           <*>         http://www.pythoncraft.com/
f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
Received on Thu Sep 29 16:51:49 2005