the timeit
module is great for testing this sort of thing:
# first case
def test1():
a=[]
for i in range(10000):
a.append(1)
# second case
def test2():
a= [0]*10000
for i in range(10000):
a[i] = 1
#list comprehension
def test3():
a = [1 for _ in range(10000)]
import timeit
n = 10000
print("appending: ",timeit.timeit(test1,number=n))
print("assigning: ",timeit.timeit(test2,number=n))
print("comprehension:",timeit.timeit(test3,number=n))
output:
appending: 13.14265166100813
assigning: 8.314113713015104
comprehension: 6.283505174011225
as requested, I replaced timeit.timeit(...)
with sum(timeit.repeat(..., repeat=7))/7
to get an average time and got this result:
appending: 12.813485399578765
assigning: 8.514678678861985
comprehension: 6.271697525575291
which is not drastically different from my original results.