I am trying to show that a iterating over a NumPy array is faster than a list. I'm doing this by creating a zero array and looping over it to increment each element, and by building a list of zeros with .append() and then looping over it a second time to increment each element. It seems to me that the array should certainly be faster here, but it's just about 2x slower! My code is:
import numpy as np
import time
N = 10000
# Check array
start = time.time()
arr = np.zeros(N, dtype = int)
for x in range(N):
arr[x] += 1
end = time.time()
print("Array op took {} seconds".format(end - start))
# Check list
start = time.time()
ls = []
for x in range(N):
ls.append(0)
for element in ls:
element += 1
end = time.time()
print("List op took {} seconds".format(end - start))
What is going wrong here? Am I just wrong in thinking that a NumPy array should be faster?
To clarify w.r.t. the duplicate flag, the other question didn't discuss traversal of a NumPy array, just its repeated instantiation. It was also about small NumPy arrays, rather than large ones.