Literals versus instantiating by name lists and dicts in Python?

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.


The difference between

my_list = list()


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


I almost never use the collection literals for empty collections in my Python code and prefer the named list, set, dict and tuple constructors instead.

The reason for this is that the literals can be quite confusing. For example, {} is not the empty set but an empty dictionary which is contrary to what anybody with a background in mathematics would intuitively expect. Also, the empty tuple () looks really awkward. Once I’m using the named constructors for sets, dictionaries and tuples, it’s only a matter of consistency to use them for lists as well, even though the empty list literal [] looks decently and I’m not aware of any bad surprises that its usage might cause.


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *