Creating a list in Python- something sneaky going on?

Those two constructs are handled quite differently:

>>> import dis
>>> def f(): return []
... 
>>> dis.dis(f)
  1           0 BUILD_LIST               0
              3 RETURN_VALUE        
>>> def f(): return list()
... 
>>> dis.dis(f)
  1           0 LOAD_GLOBAL              0 (list)
              3 CALL_FUNCTION            0
              6 RETURN_VALUE        
>>> 

The [] form constructs a list using the opcode BUILD_LIST, whereas the list() form calls the list object’s constructor.

Leave a Comment