Python provides concise literal syntax for creating empty dictionaries ({}
), lists ([]
), and tuples (()
). It
also offers a direct literal syntax for initializing dictionaries with key-value pairs (e.g., {'a': 1, 'b': 2}
).
Using the function calls dict()
, list()
, and tuple()
for these purposes is generally less preferred for a
few reasons:
- Readability and Directness: Literals are often considered more "Pythonic" and directly express the intent of creating an empty container or a
dictionary with specific initial values.
- Consistency: Python encourages the use of literals where they are clear and effective.
- Performance: Calling a function involves overhead, including name lookup for
dict
, list
, or tuple
in the
current scope. While often negligible for single calls, using literals is a direct instruction to the interpreter and can be marginally faster,
especially in performance-sensitive code or tight loops.
Specifically, the following patterns are discouraged:
- Using
dict()
to create an empty dictionary instead of {}
.
- Using
list()
to create an empty list instead of []
.
- Using
tuple()
to create an empty tuple instead of ()
.
- Using
dict(key='value', …)
to initialize a dictionary instead of {'key': 'value', …}
when keys are simple strings
valid as identifiers.
While the functional difference is minimal for creating empty collections or simple dictionaries, adopting literals promotes a more direct and
idiomatic coding style.