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