Add range check to avoid IndexError.