pythonpython-3.xlistiterablepython-internals

list() vs iterable unpacking in Python 3.5+


Is there any practical difference between list(iterable) and [*iterable] in versions of Python that support the latter?


Solution

  • list(x) is a function, [*x] is an expression. You can reassign list, and make it do something else (but you shouldn't).

    Talking about cPython, b = list(a) translates to this sequence of bytecodes:

    LOAD_NAME                1 (list)
    LOAD_NAME                0 (a)
    CALL_FUNCTION            1
    STORE_NAME               2 (b)
    

    Instead, c = [*a] becomes:

    LOAD_NAME                0 (a)
    BUILD_LIST_UNPACK        1
    STORE_NAME               3 (c)
    

    so you can argue that [*a] might be slightly more efficient, but marginally so.