ways to declare empty set variable

Boris Borcic bborcic at gmail.com
Sat Feb 16 16:03:47 CET 2008


Steve Holden wrote:
> Boris Borcic wrote:
>> bearophileHUGS at lycos.com wrote:
>>> ...Missing that, I think dict() and set() and
>>> tuple() and list() look better than using {} for the empty dict and
>>> {/} for the empty set and () for empty tuple (or {} for the empty dict
>>> and set() for the empty set).
>> The problem I have with them is in no way the looks, it is that they are not 
>> strictly equivalent as they imply dictionary lookups. Which shows in performance, eg
>>
>>  >>> import timeit
>>  >>> timeit.Timer('[]').timeit()
>> 0.22358344426456436
>>  >>> timeit.Timer('list()').timeit()
>> 0.54574505977715049
>>  >>> timeit.Timer('{}').timeit()
>> 0.21328632549668214
>>  >>> timeit.Timer('dict()').timeit()
>> 0.50557906102591232
>>
> But this is "performance" in the abstract. It's hardly going to matter 
> if you use it once in the initialization of your program, but if it 
> occurs deep inside a quadruply-nested loop that is executed 10^12 times 
> it may have an impact on performance.

In that case about 2.89 days, to be exact.

And I don't know about you, but when I write tight nested loops, I can't help 
opening an eye on not gratuitously wasting time in the innermost loops, well 
before I come to the point of measuring performance. And I find the case of [] 
vs list() (or {} vs dict()) to become a specific nuisance in that context.

> Before you have any code is exactly the *wrong* time to be considering 
> performance.

Yeah right, [] and {} are premature optimizations, one should always use list() 
or dict() unless one detains figures to justify the more exotic forms :)

> 
> regards
>   Steve

Cheers, BB




More information about the Python-list mailing list