if or exception
Christopher T King
squirrel at WPI.EDU
Thu Jul 29 09:17:00 EDT 2004
On Thu, 29 Jul 2004, Thomas Lindgaard wrote:
> Just wondering what is "the right thing to do":
>
> number = 0
> if len(list) > 0: number = anotherNumber / len(list)
>
> or
>
> try:
> number = anotherNumber / len(list)
> except:
> number = 0
The first will be faster if you expect len(list) to be zero very often,
whereas the latter will be faster if you expect it to be zero very rarely.
This is because in the normal case, the latter needs no extra code (except
a quick 'setup try block'), whereas the former requires a function call
and a comparison for all cases. In the exceptional case, the latter must
raise an catch an exception, which (I believe) is more expensive than the
check in the former. How much more expensive, I'm not qualified to say ;)
More information about the Python-list
mailing list