[Python-3000] Set literal

Ron Adam rrr at ronadam.com
Sat Jan 26 21:48:04 CET 2008



Raymond Hettinger wrote:
>> should the repr for a set be set({a, b, c}) 
>> instead of set([a, b, c])?
> 
> FWIW, running eval() on the repr is slower and less memory efficient with curly braces than with the square brackets.


This is what I get.


 >>> timeit.timeit("eval('frozenset({1,2,3})')")
48.011682987213135
 >>> timeit.timeit("eval('frozenset([1,2,3])')")
48.155133962631226
 >>> timeit.timeit("eval('frozenset((1,2,3))')")
48.062387943267822
 >>> timeit.timeit("eval('set({1,2,3})')")
46.738940000534058
 >>> timeit.timeit("eval('set([1,2,3])')")
47.597666025161743
 >>> timeit.timeit("eval('set((1,2,3))')")
47.087898969650269


It's all very close.  I think the frozenset({1,2,3}) example will get 
faster if {..} notation becomes a frozen set, and set({...}) example will 
slow down a bit.


> Also, it may be easily misread as meaning: set([frozenset([a, b, c])]).  If the latter is intended, then that would become set({{a, b, c}}) which I find hard to parse correctly.  Maybe the set([a, b, c]) form should live on.
> 
> Raymond

You added an extra level of nesting.  set(frozenset([a, b, c])) isn't any 
harder to parse (to me) than the equivalent tuple or list versions of the 
same forms: list(tuple([a, b, c]) and tuple(list([a, b, c]).


Ron



More information about the Python-3000 mailing list