12

Is there any tangible difference between the two forms of syntax available for creating empty Python lists/dictionaries, i.e.

l = list()
l = []

and:

d = dict()
d = {}

I'm wondering if using one is preferable over the other.

Jason R
  • 11,159
  • 6
  • 50
  • 81

4 Answers4

20

The function form calls the constructor at runtime to return a new instance, whereas the literal form causes the compiler to "create" it (really, to emit bytecode that results in a new object) at compile time. The former can be useful if (for some reason) the classes have been locally rebound to different types.

>>> def f():
...   []
...   list()
...   {}
...   dict()
... 
>>> dis.dis(f)
  2           0 BUILD_LIST               0
              3 POP_TOP             

  3           4 LOAD_GLOBAL              0 (list)
              7 CALL_FUNCTION            0
             10 POP_TOP             

  4          11 BUILD_MAP                0
             14 POP_TOP             

  5          15 LOAD_GLOBAL              1 (dict)
             18 CALL_FUNCTION            0
             21 POP_TOP             
             22 LOAD_CONST               0 (None)
             25 RETURN_VALUE        
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    A fun side effect of this is that if you're writing a small function that needs to cache some data between calls (perhaps a simple memoizer), you can say `def f(a, b, cache={}):` and the dict created will actually persist between calls to `f()` – robru Jun 13 '12 at 18:37
  • 7
    @Robru: This is unrelated. Using `def f(a, b, cache=dict())` also works. – Sven Marnach Jun 13 '12 at 18:40
  • FWIW, for non-empty instances, the function form may be more flexible because it may support multiple ways of specifying the object's contents, such as is the case with `dict`. – martineau Jun 13 '12 at 21:54
  • [How should I understand the output of dis.dis?](https://stackoverflow.com/questions/12673074/how-should-i-understand-the-output-of-dis-dis) – nutty about natty Jan 11 '21 at 12:19
5

The main difference is that one form includes a name lookup, while the other doesn't. Example illustrating this difference:

def list():
    return {}

print []
print list()

prints

[]
{}

Of course you definitely should not be doing such nonsense.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
2

My gut tells me that both are acceptable, so long as you're consistent.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

I am not aware of any difference, would be mostly a stylistic preference.

Levon
  • 138,105
  • 33
  • 200
  • 191