Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

What is faster a list or a numpy array for adding elements in Python

2 Answers

0 votes
import time

start = time.time()
lst = []
for i in range(100000):
    lst.append(i)
     
end = time.time()
print ("list:", end - start, "seconds")



import numpy as np
 
start = time.time()
arr = np.array([])
for i in range(50000):
    arr = np.append(arr, i)
end = time.time()
print ("numpy array:", end - start, "seconds")
 
 
 
 
'''
run:

list: 0.017374038696289062 seconds
numpy array: 2.1897921562194824 seconds

'''


 



answered Mar 3, 2023 by avibootz
0 votes
from time import process_time

start = process_time() 
lst = []
for i in range(100000):
    lst.append(i)
     
end = process_time() 
print ("list:", end - start, "seconds")



import numpy as np
 
start = process_time() 
arr = np.array([])
for i in range(50000):
    arr = np.append(arr, i)
end = process_time() 
print ("numpy array:", end - start, "seconds")
 
 
 
 
'''
run:

list: 0.016762253 seconds
numpy array: 1.9855147359999998 seconds

'''

 



answered Mar 3, 2023 by avibootz
...