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.

asked Jun 13, 2012 at 18:00
1
  • 1
    [] and {} are faster and look better in my opinion. Commented Jun 14, 2012 at 7:23

4 Answers 4

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 
answered Jun 13, 2012 at 18:03
Sign up to request clarification or add additional context in comments.

4 Comments

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: This is unrelated. Using def f(a, b, cache=dict()) also works.
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.
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.

answered Jun 13, 2012 at 18:03

Comments

2

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

answered Jun 13, 2012 at 18:02

Comments

0

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

answered Jun 13, 2012 at 18:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.