It is well known that python has no empty set literal. However, I would like to know if there is still a performant way of creating an empty set
these are a few other ways to create an empty set...
There is the pythonic way:
def f():
return set()
There is also this nasty looking way by unpacking an empty tuple:
def g():
return {*()}
You could also build a set with one item and then remove that item:
def h()
s = {1}
s.remove(1)
return s
Trying to use the literal syntax to create a set will give you a dictionary:
def i()
return {}
Interestingly, the results of dis
for each function (Python 3) are as follows:
>>> dis(f)
1 0 LOAD_GLOBAL 0 (set)
2 CALL_FUNCTION 0
4 RETURN_VALUE
>>> dis(g)
1 0 LOAD_CONST 1 (())
2 BUILD_SET_UNPACK 1
4 RETURN_VALUE
>>> dis(h)
2 0 LOAD_CONST 1 (1)
2 BUILD_SET 1
4 STORE_FAST 0 (s)
3 6 LOAD_FAST 0 (s)
8 LOAD_METHOD 0 (remove)
10 LOAD_CONST 1 (1)
12 CALL_METHOD 1
14 POP_TOP
4 16 LOAD_FAST 0 (s)
18 RETURN_VALUE
>>> dis(i)
2 0 BUILD_MAP 0
2 RETURN_VALUE
Looking at the disassemby, the pythonic way (function f
) requires two instructions, first a LOAD_GLOBAL
(which can be converted to a LOAD_FAST
if you provide set
as an argument with default value of set
), and then the function call.
Creating a dict
takes only one instruction, BUILD_MAP
.
I can see from h
that the set comprehension uses an equivalent instruction to BUILD_MAP
, BUILD_SET
, except that it first loads the constant value of (1) into the stack.
Is there a way to get Python to generate the bytecode BUILD_SET
with no elements in the stack, like how the dict comprehension generated BUILD_MAP
in function i
?