I was trying to create an example where preallocating a numpy array is quicker than using .append on a list, but ended up proving the opposite.
import numpy as np
import time
t = time.time()
emptyList = []
for i in range(int(1e8)):
emptyList.append(1)
print("Append: ", time.time() - t)
t = time.time()
emptyList = np.empty(int(1e8))
for i in range(int(1e8)):
emptyList[i] = 1
print("Preallocate: ", time.time() - t)
Which gives the following output:
Append: 12.733097314834595
Preallocate: 19.008652925491333
I'm very confused as to why appending to a list is quicker in this case. I've also tried using random numbers instead of '1' everywhere, but got the same result.