Re:Numbering should start at zero: E.W. Dijkstra
by Quekid5 on Friday March 21, 2025 @08:23AM
(#43434782)
Yes, negative indexing as in e.g. Python (so basically "from the end") can be incredibly convenient and works seamlessly when indexes are 0-based.
[ Parent
| on HN ]
Re:Numbering should start at zero: E.W. Dijkstra
by pansa2 on Friday March 21, 2025 @08:50AM
(#43435022)
Not quite seamlessly, unfortunately.
`l[:n]` gives you the first `n` elements of the list `l`. Ideally `l[-n:]` would give you the last `n` elements - but that doesn't work when `n` is zero.
I believe this is why C# introduced a special "index from end" operator, `^`, so you can refer to the end of the array as `^0`.
Re:Numbering should start at zero: E.W. Dijkstra
by UncleEntity on Friday March 21, 2025 @09:21AM
(#43435347)
So you're saying a negative index value should work like a count of elements to return and not an index?
Then you couldn't do thing like l[-4:-2] to get a range of elements which seems slightly useful.
Re:Numbering should start at zero: E.W. Dijkstra
by pansa2 on Friday March 21, 2025 @09:27AM
(#43435403)
No - negative indexing is fine as it is. You just need to be careful about the special case of negative zero.
Re:Numbering should start at zero: E.W. Dijkstra
by Ukv on Friday March 21, 2025 @09:31AM
(#43435467)
> Yes, negative indexing as in e.g. Python (so basically "from the end") can be incredibly convenient and works seamlessly when indexes are 0-based.
I'd claim 0-based indexing actually throws an annoying wrench in that. Consider for instance:
for n in [3, 2, 1, 0]:
start_window = arr[n: n+5]
end_window = arr[-n-5: -n]
The start_window indexing works fine, but end_window fails when n=0 because -0 is just 0, the start of the array, instead of the end. We're effectively missing one "fence-post". It'd work perfectly fine with MatLab-style (1-based, inclusive ranges) indexing.