Given a list of integers (list_nb) of fixed size (n), what is the best way to reset (re-initialize) all the values to 0.
I already tried two methods, 1) using a loop to reset all elements one by one, 2) a new list with the same size (where all elements are at 0).
The second method clearly gives better results in terms of execution time.
import time
n = 200_000_000
list_nb = [0]*n
# some lines of code that change the list_nb ....
# method 1 to reset
start_time = time.time()
for i in range(len(list_nb)):
list_nb[i] = 0
end_time = time.time()
print("Method 1 time = ",end_time-start_time," s")
# method 2 to reset
start_time = time.time()
list_nb = [0]*n
end_time = time.time()
print("Method 2 time = ",end_time-start_time," s")
Result:
- Method 1 time = 16.05620765686035 s
- Method 2 time = 1.279524564743042 s
I don't know if there is any other way to do it.
Thanks.