Python Coding Style – Literals vs Instantiating by Name Lists and Dicts

coding-stylepython

In Python, what is the difference in these declarations…

my_list = []
my_list = list()

…and in these?

my_dict = {}
my_dict = dict()

Are they interpreted the same, and why would you use one over the other? I haven't seen or noticed a difference.

Best Answer

The difference between

my_list = list()

and

my_list = []

is that list requires a namespace lookup, first in the module level globals, then in the builtins.

On the other hand, [] is a list literal and is parsed as creating a new list from the language, which doesn't require any name lookups. So the literal is faster on object creation.

Otherwise, they are both the same, for empty lists.

The same analogously applies to dict() and {}.

(Slightly beyond the scope of the question, but the difference, as constructors of non-empty lists, is that list() takes an iterable to construct the list, and [] constructs the list with only the objects with which you create it, usually literals.)

Related Topic