Check if dictionary empty with == {}
Steven D'Aprano
steve at pearwood.info
Thu Aug 20 13:44:02 EDT 2015
On Thu, 20 Aug 2015 11:54 pm, Skip Montanaro wrote:
> On Wed, Aug 19, 2015 at 10:16 PM, Steven D'Aprano <
> steve+comp.lang.python at pearwood.info> wrote:
>
>> So maybe it's a micro-optimization?
>
>
> Note, however, that the original post compared "mydict == {}" with "not
> mydict". In that case, it's decidedly not an optimization:
>
> firefly% python2.7 -m timeit -s "mydict = {1:2}" "if mydict == {}: pass"
> 10000000 loops, best of 3: 0.0508 usec per loop
> firefly% python2.7 -m timeit -s "mydict = {1:2}" "if not mydict: pass"
> 10000000 loops, best of 3: 0.0246 usec per loop
I suppose it depends on whether you want to run the "if" block when mydict
is None, 0, [], "", etc.
Testing for "any Falsey value" and "an empty dict" are not the same,
naturally they will perform differently.
--
Steven
More information about the Python-list
mailing list