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

Aahz aahz at pythoncraft.com
Sun Jul 10 09:21:02 EDT 2005


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

In article <roy-044F62.15060709072005 at reader2.panix.com>,
Roy Smith  <roy at 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 at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.



More information about the Python-list mailing list