I was interested in finding the fastest way to initialize an empty set in Python (I'm using 3.8). You cannot instantiate an empty set as {}
as that creates a dict
, so what is generally recommended is to use the set()
constructor. I noticed the other day that there is another way to instantiate an empty set: you can unpack an empty tuple ()
into the {...}
syntax for sets as follows: {*()}
. Timing this with the timeit
module in ipython
gives the following results:
%timeit {*()}
67.7 ns ± 1.68 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit set()
84.5 ns ± 2.57 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
I find this pretty peculiar - the more elegant set()
constructor takes 25% more time relative to {*()}
. The same observations have been made in the past with, e.g., []
vs. list()
and {}
vs. dict()
.
%timeit []
17.8 ns ± 0.791 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
%timeit list()
81 ns ± 1.56 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit {}
18.6 ns ± 0.575 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
%timeit dict()
98.6 ns ± 5.09 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
It is rather easy to switch to the primitive syntax {}
and []
for list
s and dict
s, but what I've found for sets is obviously not as clean. I'm curious as to insights into this (in general).