Re:Again on 0-based vs. 1-based indexing
by KarlKode on Wednesday January 20, 2021 @06:05AM
(#25844964)
But shouldn't it be [-0] to get the last element if [0] denotes the first element?
[ Parent
| on HN ]
Re:Again on 0-based vs. 1-based indexing
by codeflo on Wednesday January 20, 2021 @06:22AM
(#25845093)
I think the most mathematically natural way to interpret negative indices is to threat them as numbers modulo list length. Then 0 = length, and -1 = length - 1.
Re:Again on 0-based vs. 1-based indexing
by bvrmn on Wednesday January 20, 2021 @01:09PM
(#25849744)
C programmers can give you a couple of advises about "correct" modulo on negative numbers.
Re:Again on 0-based vs. 1-based indexing
by nemetroid on Wednesday January 20, 2021 @06:33AM
(#25845159)
Negative indices have an implied ”len(list)” in front of them. They can be seen as an application of the idea of half-open intervals (0 <= i < len(list)), so it makes sense that they’re not symmetrical.
Re:Again on 0-based vs. 1-based indexing
by naniwaduni on Wednesday January 20, 2021 @08:13AM
(#25845997)
Is this sensible, or is it an unprincipled ad-hoc justification for a feature that happens to be useful?
Or another way: Is this more reasonable than, say, implicitly taking indices mod len(list)? How about implicitly flooring indices? If so, why?
Re:Again on 0-based vs. 1-based indexing
by nemetroid on Wednesday January 20, 2021 @09:16AM
(#25846655)
I'm not sure on what principles you'd make a principled justification. My most common use of negative indices is for slicing the end of the list, in which context the interpretation similar to len(list) makes sense. E.g., list[:-2] does what you'd expect (the same as list[2:], except from the other end).
> implicitly taking indices mod len(list)?
Isn't this doing that (plus some bounds checking)? -1 mod 4 evaluates to 3.
> implicitly flooring indices?
Not sure I understand what this means.