Home >Backend Development >Python Tutorial >How to initialize a list in Python?

How to initialize a list in Python?

青灯夜游
青灯夜游Original
2019-03-19 12:00:0815907browse

Python is a very flexible language and can perform a single task in many ways, for example, an initialization list can be performed in many ways. The following article will introduce you to several Python initialization methods and compare the efficiency of these methods. I hope it will be helpful to you.

How to initialize a list in Python?

#Now we will introduce some methods of initializing a list in Python (we create a list with a size of 1000 and initialize it with zero).

Method 1: Using for loop and append()

We can create an empty list and use the append() method to pass the for Loop n times to add elements to the list.

arr = []
for i in range(1000):
    arr.append(0)

Method 2: Use a while loop with a counter variable and append()

This is somewhat similar to method 1, but we use while loop instead of for loop.

arr = []
i = 0
while(i<1000):
    arr.append(0)

Method 3: Use List Comprehension

List Comprehension is a method used by mathematicians to implement well-known notations The Pythonic way of collecting. It consists of square brackets containing an expression, followed by a for clause, followed by an optional if clause.

The expression can be any type of object we want to put into the list; since we initialized the list with zero, our expression will only be 0.

arr = [0 for i in range(1000)]

Note: List derivation can be used to write efficient code, and its execution speed is 35% faster than the for loop.

Method 4: Use the * operator

The operator can be used as [object] * n, where n is the number of elements in the array .

arr = [0]*1000

Comparison of code execution time

Let’s take a look at the execution time of these four methods to see which method is faster.

Example: We will calculate the average time each method takes to initialize an array of 10,000 elements 500 times.

# 导入时间模块以计算时间
import time 
  
# 初始化列表以保存时间
forLoopTime = [] 
whileLoopTime = [] 
listComprehensionTime = [] 
starOperatorTime = [] 
  
# 重复此过程500次,并计算所用的平均时间。
for k in range(500):  
  
    # 开始时间
    start = time.time() 
    # 声明空列表
    a = [] 
    # 执行for循环10000次
    for i in range(10000): 
        a.append(0) 
    # 停止时间
    stop = time.time() 
    forLoopTime.append(stop-start) 
  
    # 开始时间
    start = time.time() 
    # 声明空列表
    a = [] 
    i = 0
    # 执行while循环10000次
    while(i<10000): 
        a.append(0) 
        i+= 1
    stop = time.time() 
    whileLoopTime.append(stop-start) 
  
    start = time.time() 
    # 使用列表推导(List Comprehension) 来初始化列表
    a = [0 for i in range(10000)]  
    stop = time.time() 
    listComprehensionTime.append(stop-start) 
  
  
    start = time.time() 
    # 使用*运算符
    a = [0]*10000 
    stop = time.time() 
    starOperatorTime.append(stop-start) 
  
  
  
print("for循环所用的平均时间:" + str(sum(forLoopTime)/100)) 
print("while循环所用的平均时间:" + str(sum(whileLoopTime)/100)) 
print("列表推导所用的平均时间:" + str(sum(listComprehensionTime)/100)) 
print("* 运算符所用的平均时间: " + str(sum(starOperatorTime)/100))

Output:

How to initialize a list in Python?

Note: Times will vary depending on the platform this code is executed on. These times are only used to study the relative performance of these initialization methods.

● It can be seen that the time taken by the for and while loops is almost the same.

● The performance of list comprehension is much better than for and while loops, the former is 3-5 times faster. Another example of this difference can be seen when we try to create a list of numbers from 1-1000. Using a list comprehension is much better than using append().

a = [i for i in range(1,1001)]

● Using the * operator is faster than the rest, this is how you should initialize the list

Related video tutorial recommendations: "Python Tutorial"

The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to initialize a list in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn