I am working on the following Python list exercise from codingbat.com:
Given an array of ints, return the sum of the first 2 elements in the array.
If you can't use sum, one possible solution uses exceptions:
totalsum = 0 try: totalsum += nums[0] totalsum += nums[1] except IndexError: pass return totalsum
Catch the error and short-circuit the summation if an element doesn't exist. Easier to ask forgiveness than permission, as they say.