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

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Feb 15 07:14:46 EST 2006


On Wed, 15 Feb 2006 08:44:10 +0100, Marc 'BlackJack' Rintsch wrote:

> In <1139976842.179801.285400 at z14g2000cwz.googlegroups.com>, Farel wrote:
> 
>> Which is Faster in Python and Why?
> 
> ``if not b in m`` looks at each element of `m` until it finds `b` in it
> and stops then.  Assuming `b` is in `m`, otherwise all elements of `m` are
> "touched".
> 
> ``if m.count(b) > 0`` will always goes through all elements of `m` in the
> `count()` method.

But the first technique executes in (relatively slow) pure Python, while
the count method executes (relatively fast) C code. So even though count
may do more work, it may do it faster.

The only way to tell for sure is to actually time the code, not try to
guess.



-- 
Steven.




More information about the Python-list mailing list