On Sun, 23 Mar 2008 10:45:38 -0700, Paul Rubin wrote:

> John Nagle <[EMAIL PROTECTED]> writes:
>>    What's the cheapest way to test for an empty dictionary in Python?
>> 
>>      if len(dict.keys() > 0) :
> 
> I like to think len(dict) is constant time but I haven't checked the
> code. Same for bool(dict) (which is what you get when you run "if dict:
> ...").

Except that "if dict" doesn't needlessly and wastefully create a bool.

>>> from timeit import Timer
>>> Timer("if {1:2}: pass").timeit()
1.1590199184417725
>>> Timer("if bool({1:2}): pass").timeit()
1.8825540542602539


Python knows the truth value of built-in types like dicts without 
actually converting them to bools, or for that matter calling __len__ or 
__nonzero__ on them.




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to