I have written basic python snippets to first insert values in a list and then reverse them. I found that there was a huge difference of speed of execution between insert and append methods.
Snippet 1:
L = []
for i in range(10**5):
L.append(i)
L.reverse()
Time taken to execute this :
real 0m0.070s
user 0m0.064s
sys 0m0.008s
Snippet 2:
l = []
for i in range(10**5):
l.insert(0,i)
Time taken to execute:
real 0m5.645s
user 0m5.516s
sys 0m0.020s
I expected the snippet 2 to perform much better than snippet1, since I am performing the reverse operation directly by inserting the numbers before. But the time taken says otherwise. I fail to understand why the latter method takes more time to execute, even though the method looks more elegant. Does any one have any explanation for this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…