Whenever a function retrieves a list element outside of loop, you should wrap the reference in a try block instead of testing the length of the list (because you will probably forget to subtract one in your test, introducing a but). For example:
These are safe:
This is a bug that will give an error sometimes:
As you can see, both the if block and the try block have the same number of lines and structure, but try reduces the number of references to someList, doesn't need to call len() and protects you from a simple mistake.
These are safe:
Code:
# inside a loop for item in someList: # use items from list sequentially try: item = someList[index] except IndexError: # handle out-ot-range index if index < len(someList): item = someList[index] else: # handle out-of-range index
Code:
if index > len(someList): # should be len(someList) - 1 # handle out-ot-range index else: item = someList[index]
Comment