I was wondering why the try-except is slower than the if in the program below.
def tryway():
try:
while True:
alist.pop()
except
There is still faster way iterating with for, though sometimes we want list to physically shirink so we know how many are left. Then alist should be parameter to the generator. (John is also right for while alist:
) I put the function to be a generator and used list(ifway()) etc. so the values are actualy used out of function (even not used):
def tryway():
alist = range(1000)
try:
while True:
yield alist.pop()
except IndexError:
pass
def whileway():
alist = range(1000)
while alist:
yield alist.pop()
def forway():
alist = range(1000)
for item in alist:
yield item
if __name__=='__main__':
from timeit import Timer
print "Testing Try"
tr = Timer("list(tryway())","from __main__ import tryway")
print tr.timeit(10000)
print "Testing while"
ir = Timer("list(whileway())","from __main__ import whileway")
print ir.timeit(10000)
print "Testing for"
ir = Timer("list(forway())","from __main__ import forway")
print ir.timeit(10000)
J:\test>speedtest4.py
Testing Try
6.52174983133
Testing while
5.08004508953
Testing for
2.14167694497