Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing empty Python data structures

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.

like image 742
Jason R Avatar asked Jun 13 '12 18:06

Jason R


1 Answers

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        
like image 85
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 23:09

Ignacio Vazquez-Abrams