Negative indexing in Python - Python - Data Science Dojo Discussions
python - Negative list index? - Stack Overflow
Lol, python uses 0-based indexing, but 1-based negative indexing.
The negative index starts at the beginning of the array too. So you have to go negative one more step to pass the last element.
0 1 2 3
a b c
In the illustration a is indexed [0] by the number to the left of it. If you count backwards:
-3 -2 -1 -0 1 2 3
a b c a b c
Here c is index -1 by the number to the left of it as well. It is consistent behavior.
Regarding list slicing: can anyone help me understand the reasoning behind inclusive vs. exclusive indexing with negative vs. non-negative integers?
Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.
List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.