30

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
  • 20,142
  • 17
  • 60
  • 81
lang2
  • 10,393
  • 16
  • 76
  • 123

3 Answers3

33

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).

tckmn
  • 55,458
  • 23
  • 108
  • 154
28

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
  • 3,913
  • 6
  • 35
  • 49
  • 5
    I would argue this is the most important distinction, since it is the one that actually produces different results. – SethMMorton Nov 15 '15 at 05:14
  • 1
    This holds for any iterable. – orlp Nov 15 '15 at 05:31
  • 2
    Totally agree with @SethMMorton: `list()` accepts only iterables as an argument, while `[]` simply wraps whatever you'll throw at it with a list. So, if you'll try to run `list(1)` you'll get an exception since `int` is not iterable, while `[1]` will work just fine. It also explains the unpacking property! – Nir Alfasi Oct 13 '17 at 23:34
  • 1
    Another distinction is when you call both on the function map(). One will convert the object into a list while the other will simply wrap the object by []. – Dr. Younes Henni Jan 26 '18 at 12:56
18

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

[] is always a list literal.

orlp
  • 106,415
  • 33
  • 201
  • 300
  • 12
    Note that only terrible people override `list`. (It's a good point, though.) :P – tckmn Nov 15 '15 at 04:28
  • @Doorknob: From the look of all the questions on SO where `list` (and `str` and `dict`) get used as variable names, I tend to agree. :) – PM 2Ring Nov 15 '15 at 05:29