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

Georg Brandl g.brandl-nospam at gmx.net
Wed Feb 15 11:01:02 EST 2006


Steven D'Aprano wrote:
> 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.

Why does "not b in m" execute in pure Python? list.__contains__ is implemented
in C code as well as list.count.

Georg



More information about the Python-list mailing list