Using list/set/dict literal syntax is simpler and computationally quicker than calling list()
, set()
, or dict()
.
A literal is a terse and easily understood way to write a value without having to call the Python builtin function. A literal is syntax that the parser recognises as writing an object directly. Some examples of literal syntax:
datatype | builtin call | literal syntax |
---|---|---|
tuple | tuple([1, 2, 3]) | (1, 2, 3) |
list | list([1, 2, 3]) | [1, 2, 3] |
set | set([1, 2, 3]) | {1, 2, 3} |
dict | dict(a=2) | {'a': 2} |
bytes | bytes('\x00', 'utf8') | b'\x00' |
int | int('42') | 42 |
float | float('4.2') | 4.2 |
bool | bool(1) | True |
Calling dict()
, list()
, and set()
is slower than using the literal syntax, because the function name must be looked up in the global scope.
There is also the risk that dict()
, list()
, and set()
have been rebound e.g, poor naming choices may result in a developer writing list = [1, 2, 3]
. This is poor naming decisions, but would you expect poor naming decisions break the code?
Given that these are completely equivalent:
Why not choose the easiest to read, write, and quickest to execute (the first one)?
If our GitHub code review bot spots this issue in your pull request it gives this advice:
1 | + | values = list([1, 2, 3]) |
Using list/set/dict literal syntax is simpler and computationally quicker than calling list()
, set()
, or dict()
.
- | values = list([1, 2, 3]) |
+ | values = [1, 2, 3] |