Fixed the off-by-one error and made the code more pythonic.