Python - Which is faster to initialize lists?

PythonServer Side ProgrammingProgramming

Python is a very flexible language where a single task can be performed in a number of ways, for example initializing lists can be performed in many ways. However, there are subtle differences in these seemingly similar methods. Python which is popular for its simplicity and readability is equally infamous for being slow compared to C++ or Java. The ‘for’ loop is especially known to be slow whereas methods like map() and filter() known to be faster because they are written in C.


 Live Demo

# import time module to calculate times
import time
# initialise lists to save the times
forLoopTime = []
whileLoopTime = []
listComprehensionTime = []
starOperatorTime = []
# repeat the process for 500 times
# and calculate average of times taken.
for k in range(500):
   # start time
   start = time.time()
   # declare empty list
   a = []
   # run a for loop for 10000 times
   for i in range(10000):
   # stop time
   stop = time.time()
   # start time
   start = time.time()
   # declare an empty list
   a = []
   i = 0
   # run a for loop 10000 times
      i+= 1
   stop = time.time()
   start = time.time()
   # list comprehension to initialize list
   a = [0 for i in range(10000)]
   stop = time.time()
   start = time.time()
   # using the * operator
   a = [0]*10000
   stop = time.time()
print("Average time taken by for loop: " + str(sum(forLoopTime)/100))
print("Average time taken by while loop: " + str(sum(whileLoopTime)/100))
print("Average time taken by list comprehensions: " + str(sum(listComprehensionTime)/100))
print("Average time taken by * operator: " + str(sum(starOperatorTime)/100))    


Average time taken by for loop: 0.00623725175858
Average time taken by while loop: 0.00887670278549
Average time taken by list comprehensions: 0.00318484544754
Average time taken by * operator: 0.000371544361115
Updated on 08-Aug-2020 08:11:16