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

Question:

What’s the difference between the following code:

foo = list()

And

foo = []

Python suggests that there is one way of doing things but at times there seems to be more than one.

Asked By: lang2

||

Answers:

list is a global name that may be overridden during runtime. list() calls that name.

[] is always a list literal.

Answered By: orlp

One’s a function call, and one’s a literal:

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

Use the second form. It’s more Pythonic, and it’s probably faster (since it doesn’t involve loading and calling a separate funciton).

Answered By: tckmn

For the sake of completion, another thing to note is that list((a,b,c)) will return [a,b,c], whereas [(a,b,c)] will not unpack the tuple. This can be useful when you want to convert a tuple to a list. The reverse works too, tuple([a,b,c]) returns (a,b,c).

Edit: As orlp mentions, this works for any iterable, not just tuples.

Answered By: Andrew Sun
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.