On Thu, Nov 26, 2020 at 01:27:46PM +1300, Greg Ewing wrote:
On 26/11/20 12:41 pm, Steven D'Aprano wrote:
a = "abcdef" a[-2] # returns a result
Yes, but did you *intend* that result, or did the -2 result from a calculation that should have returned a positive index but went wrong? Python has no way to tell.
Ah, now the penny drops! You are suggesting that the negative index might be a miscalculation. Okay, fair enough. Be happy that if the index is *sufficiently* negative, it will still raise an out-of-bounds IndexError. But is there something fundamentally harder about verifying your calculation in the half-open interval `-n <= index < n` versus the half-open interval `0 <= index n`? I don't think there is. Personally, I have miscalculated indices and got the wrong *postive*, but still within bounds, value far more than an unwanted negative value. E.g. I expected to calculate an index of 3, but got 7 instead. That's much harder to test against than an unwanted negative: assert index >= 0 and the problem is solved. In any case, as you correctly point out, we're not going to dump negative indices, so this discussion is rather hypothetical. -- Steve