What’s the difference between list() and []

What are the key differences between using list() and []?

The most obvious and visible key difference between list() and [] is the syntax. Putting the syntax aside for a minute here, someone whose new or intermediately exposed to python might argue that they’re both lists or derive from the same class; that is true. Which furthermore increases the importance of understanding the key differences of both, most of which are outlined below.

list() is a function and [] is literal syntax.

Literal syntax
Literal Syntax – src:excess.org
Function
Function – src:excess.org

Let’s take a look at what happens when we call list() and [] respectively through the disassembler.

>>> import dis
>>> print(dis.dis(lambda: list()))
  1           0 LOAD_GLOBAL              0 (list)
              3 CALL_FUNCTION            0 (0 positional, 0 keyword pair)
              6 RETURN_VALUE
None
>>> print(dis.dis(lambda: []))
  1           0 BUILD_LIST               0
              3 RETURN_VALUE
None
The output from the disassembler above shows that the literal syntax version doesn’t require a global lookup, denoted by the op code LOAD_GLOBAL or a function call, denoted by the op code CALL_FUNCTION.

As a result, literal syntax is faster than it’s counterpart. – Let’s take a second and look at the timings below.

import timeit
>>> timeit.timeit('[]', number=10**4)
0.0014592369552701712
>>> timeit.timeit('list()', number=10**4)
0.0033833282068371773
On another note it’s equally important and worth pointing out that literal syntax, [] does not unpack values. An example of unpacking is shown below.

>>> list('abc') # unpacks value
['a', 'b', 'c']
>>> ['abc'] # value remains packed
['abc']

What’s a literal in python?

Literals are notations or a way of writing constant or raw variable values which python recognises as built-in types.


It has been fun and interesting to write the first of many to come PythonRight blog posts; in the next blog post we’ll be going over the beauty of unpacking , so stay tuned. 😉 – If you have any feedback or any other topics that you’d like to see explained in detail, do feel free to comment.