4 ms·
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.
by Quekid5 2y ago
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.
- pansa2 2y agoNot 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`.
- UncleEntity 2y agoSo 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.
- pansa2 2y agoNo - negative indexing is fine as it is. You just need to be careful about the special case of negative zero.
- Ukv 2y ago> 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.