I was wondering why the try-except is slower than the if in the program below.
def tryway():
try:
while True:
alist.pop()
except
If you are really interested in speed, both of your contestants could do with losing some weight.
while True: is slower than while 1: -- True is a global "variable" which is loaded and tested; 1 is a constant and the compiler does the test and emits an unconditional jump.
while True: is redundant in ifway. Fold the while/if/break together: while alist != []:
while alist != []: is a slow way of writing while alist:
Try this:
def tryway2():
alist = range(1000)
try:
while 1:
alist.pop()
except IndexError:
pass
def ifway2():
alist = range(1000)
while alist:
alist.pop()
`