Which is faster? (if not b in m) or (if m.count(b) > 0)

Delaney, Timothy (Tim) tdelaney at avaya.com
Sun Feb 19 18:08:48 EST 2006


Farel wrote:

> Tim, Are you saying that:
>      not (b in m)
> is faster than:
>     b not in m

On the contrary. `not (b in m)` requires negating the result of `b in m`
(via an additional bytecode operation). `b not in m` doesn't. However,
the difference in performance is minimal, as testing using the timeit
module will show you.

The important difference is the improvement in clarity. There is no
possibility for misinterpretation as to the meaning of `b not in m`,
whereas with the original `not b in m` I had to actually go check the
precedence rules to be sure what would happen. Adding the parentheses
makes it clear, but doesn't read as well as using the `not in` operator.

As others have said, if you really care about the performance of
something, the timeit module is your friend. Discussions about *why* you
get certain performance results are then useful.

Tim Delaney



More information about the Python-list mailing list