Search code examples
pythonpython-internals

How are lists created without the class name?


It is possible to go about creating lists like this:

l = list()

l.append(1)

however the most common method is to create a list like this:

l = [1]

My question is simple in the concept but probably extremely complicated in the answer but how is it that the list is created with a notation outside the usual class notation?

I have looked through the source code at https://github.com/python/cpython/blob/master/Objects/listobject.c and cant find where it defines the list notation [].

I am not asking about the difference between [] and list() - I am asking why you can use [] at all. How is it possible that this object is created differently from other objects?


Solution

  • The list literal [...] is defined by the grammar, the same as keywords like if and while:

    atom: ... | '[' [testlist_comp] '] | ...
    

    When the code generator encounters a list literal in the AST, it generates a specific byte code to create a list:

    >>> import dis
    >>> dis.dis('[]')
      1           0 BUILD_LIST               0
                  2 RETURN_VALUE
    

    whereas a call to list is handled like any other callable:

    >>> dis.dis('list()')
      1           0 LOAD_NAME                0 (list)
                  2 CALL_FUNCTION            0
                  4 RETURN_VALUE
    

    For non-empty lists, the expressions in the literal are added to the stack for BUILD_LIST to use:

    >>> dis.dis('list([1,2])')
      1           0 LOAD_NAME                0 (list)
                  2 LOAD_CONST               0 (1)
                  4 LOAD_CONST               1 (2)
                  6 BUILD_LIST               2
                  8 CALL_FUNCTION            1
                 10 RETURN_VALUE
    

    A call like list([1,2]) necessarily uses BUILD_LIST first to create a list before passing that to list as an argument.