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.
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        
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With