Is there any tangible difference between the two forms of syntax available for creating empty Python lists/dictionaries, i.e.
l = list()
l = []
and:
d = dict()
d = {}
I'm wondering if using one is preferable over the other.
4 Answers 4
The function form calls the constructor at runtime to return a new instance, whereas the literal form causes the compiler to "create" it (really, to emit bytecode that results in a new object) at compile time. The former can be useful if (for some reason) the classes have been locally rebound to different types.
>>> def f():
... []
... list()
... {}
... dict()
...
>>> dis.dis(f)
2 0 BUILD_LIST 0
3 POP_TOP
3 4 LOAD_GLOBAL 0 (list)
7 CALL_FUNCTION 0
10 POP_TOP
4 11 BUILD_MAP 0
14 POP_TOP
5 15 LOAD_GLOBAL 1 (dict)
18 CALL_FUNCTION 0
21 POP_TOP
22 LOAD_CONST 0 (None)
25 RETURN_VALUE
4 Comments
def f(a, b, cache={}): and the dict created will actually persist between calls to f()def f(a, b, cache=dict()) also works.dict.The main difference is that one form includes a name lookup, while the other doesn't. Example illustrating this difference:
def list():
return {}
print []
print list()
prints
[]
{}
Of course you definitely should not be doing such nonsense.
Comments
My gut tells me that both are acceptable, so long as you're consistent.
Comments
I am not aware of any difference, would be mostly a stylistic preference.
[]and{}are faster and look better in my opinion.