Use literals instead of calling list/set/dict

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:

datatypebuiltin callliteral syntax
tupletuple([1, 2, 3])(1, 2, 3)
listlist([1, 2, 3])[1, 2, 3]
setset([1, 2, 3]){1, 2, 3}
dictdict(a=2){'a': 2}
bytesbytes('\x00', 'utf8')b'\x00'
intint('42')42
floatfloat('4.2')4.2
boolbool(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:

code-review-doctorbotsuggested changes just now
helpers.py
1
+
values = list([1, 2, 3])
Suggested changes
-
values = list([1, 2, 3])
+
values = [1, 2, 3]
Commit suggestion

Using list/set/dict literal syntax is simpler and computationally quicker than calling list(), set(), or dict().

Read more
Update helpers.py
We're your Python code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

Code Review Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code use-comprehension in your pyproject.toml file.

Read more about configuring Code Review Doctor.