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:
I don't know if there is any other way to do it.
Thanks.
Method 2 is clearly superior on speed, and it's easy to understand for anyone familiar with Python sequence multiplication. A warning: It's not resetting the contents of the list
; it's making a whole new list
and rebinding the name to that new list
. So if list_nb
was an argument to a function, the caller's copy of the list
would not be changed. If that's what you want, great, but if you want the contents to be changed in place, change it to:
list_nb[:] = [0]*n # Or itertools.repeat(0, n), though CPython doesn't speed it up
which uses slice assignment to replace the contents of the existing list
in-place. It takes about twice as long (it builds a new list
, copies from it, then throws it away) as list_nb = [0]*n
, but if you need in-place mutation, it's worth it.
I think the best way to do it is overwriting the list as you did in method #2. It's easier to overwrite the existing list than replacing every element in the list with 0. I believe there is no faster way to do it, but I might be wrong. Nice job !
Using numpy is pretty quick.
import numpy as np
import time
n= 200000000
start_time = time.time()
list_nb = np.zeros(n)
end_time = time.time()
print(end_time-start_time)
This takes me 0.003000497817993164
If you are ready to use numpy:
start_time = time.time()
a = numpy.zeros(n, dtype=object)
end_time = time.time()
print("Method 0 time = ",end_time-start_time," s")
gives
('Method 0 time = ', 0.8265918731689453, ' s')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.