Several methods of initializing a list in Python

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:

  1. Use loops for initialization

Code:

1
2
3
lst = []
for i in range(1000000):
lst.append(0)
  1. Use [ value for i in range(length)]

Code:

1
lst = [0 for i in range(1000000)]
  1. Use [value] * length

Code:

1
lst = [0] * 1000000

Performance comparison

Use the following code snippet:

1
2
3
4
5
6
import time

start = time.time()
# ... Different test code
end = time.time()
print("time is: ", (end - start) * 1000)

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.

本文标题:Several methods of initializing a list in Python

文章作者:Morning Star

发布时间:2022年01月05日 - 15:01

最后更新:2022年01月05日 - 17:01

原始链接:https://www.mls-tech.info/python/python-init-list-method-en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。