33

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.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
lang2
  • 11,433
  • 18
  • 83
  • 133

3 Answers3

35

One is a function call, and the other is 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 function).

Mortbros
  • 3
  • 3
tckmn
  • 57,719
  • 27
  • 114
  • 156
29

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.

Andrew Sun
  • 4,101
  • 6
  • 36
  • 53
18

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

[] is always a list literal.

orlp
  • 112,504
  • 36
  • 218
  • 315