Creating a list in Python- something sneaky going on?
No, Python does not call list()
, or you could affect what type []
creates by assigning to list, which you cant:
>>> import __builtin__
>>> __builtin__.list = set
>>> list()
set([])
>>> []
[]
[]
is syntax for creating a list. It's a builtin type and it has special syntax, just like dicts and strings and ints and floats and lots of other types.
Creating instances of types can also be done by calling the type, like list()
-- which will in turn call the type's constructor and initializer for you. Calling the initializer (__init__
) directly does not create a new instance of the type. Calling the constructor (__new__
) does, but you should not be calling it directly.
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.