1. Collection initialization
When initializing empty Python collections such as lists and dictionaries, favor using the corresponding literal delimiters instead of the corresponding functions.
Literals are shorter, more familiar to most readers, and emphasize the shape of the value immediately. They also avoid looking like a conversion from another iterable when you are simply creating an empty collection.
1.1. Don’t do this
1names = list() # initialize list
2data = dict() # initialize dictionary
1.2. Do this
1names = [] # initialize list
2data = {} # initialize dictionary
Using the literal delimiters [] and {} is faster and more Pythonic than using list() and dict(). The literal form is faster because the generated bytecode does not need to look up a function name.
You can inspect the bytecode for [] as follows.
1from dis import dis
2
3dis('[]')
The bytecode looks like this. Notice that there are only two lines.
11 0 BUILD_LIST 0
2 2 RETURN_VALUE
You can inspect the bytecode for list() as follows.
1from dis import dis
2
3dis('list()')
The bytecode looks like this. Notice that there are three lines.
11 0 LOAD_NAME 0 (list)
2 2 CALL_FUNCTION 0
3 4 RETURN_VALUE
Here’s the bytecode for {}.
11 0 BUILD_MAP 0
2 2 RETURN_VALUE
Here’s the bytecode for dict().
11 0 LOAD_NAME 0 (dict)
2 2 CALL_FUNCTION 0
3 4 RETURN_VALUE