This article describes the initialization methods of List in Python and makes a simple comparison of the performance of these methods.
Initialization method
Initialization in this article refers to initializing a list with specific values. For example, to initialize a list with a length of 1000000 with 0, you can use the following methods:
- Use loops for initialization
Code:
1 | lst = [] |
- Use [ value for i in range(length)]
Code:
1 | lst = [0 for i in range(1000000)] |
- Use [value] * length
Code:
1 | lst = [0] * 1000000 |
Performance comparison
Use the following code snippet:
1 | import time |
A simple count of performance can be made, and the result is:
The time of method 1 is: 135 ms
The time of method 2 is: 59 ms
The time of method 3 is: 3 ms
The third method has clear performance advantages.
The above method can also be used to initialize mostly a List, and the initial value can be None.