Which method for arrays is faster ? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Which method for arrays is faster ? (/thread-34773.html) |
Which method for arrays is faster ? - thunderspeed - Aug-30-2021 Hello everyone, I hope you are well. I wonder which of those two methods for dealing with arrays would be faster in python: method 1: define array at the beginning of the code as np.zeros for example, then fill the elements x[1] , x[2] ... etc, within the code. method 2: define array at the beginning of the code as empty array: x = [] , and then fill the elements x[1] , x[2] ... etc, within the code. Thanks RE: Which method for arrays is faster ? - deanhystad - Aug-31-2021 You should time it. import timeit test_setup = "import numpy as np" test_code = ''' x = np.zeros(100000) for i in range(len(x)): x[i] = i ''' print('np.zeros', timeit.timeit(stmt=test_code, setup=test_setup, number=1000)) test_setup = "" test_code = ''' x = [] for i in range(100000): x.append(i) ''' print('append', timeit.timeit(stmt=test_code, setup=test_setup, number=1000)) RE: Which method for arrays is faster ? - DeaD_EyE - Aug-31-2021 Scenario 1: You make a list and fill it with data. Task done. Scenario 2: You've to repeat this one million times. If scenario 2 is the case, then preallocate the numpy.array once.Then you can work with the same list one million times without creating new lists/arrays. Of course, this depends on the algorithm you're using. Allocating memory is slow. |