+ 1
How does negative indexing work?
I'm a fairly experienced programmer, mostly in Python which is the main subject today. How does it work, when does the index start, what enc does it start from? I've never bothered to use it honestly because I didn't care for it, and now I have zero clue what it is or how to use it.
5 Réponses
+ 1
first index : 0
seventh index: 6
last index : -1
penultimate index : -2
I hope this helps
+ 1
If you have a string or a list, then the last element has index of -1, and second to last has index of -2 and so on, even though it also has a positive index number.
+ 1
# Hi Xmosity ,
# You can use this function to see how it works:
def neg_inx(positive_index, length_of_list):
"""Transform a positive index to its negative counterpart.
A negative index starts counting from the end of the list.
"""
return positive_index - length_of_list
# https://sololearn.com/compiler-playground/c8s8616Zccao/?ref=app
0
Thanks!
0
Say you have a `list` with five items in...
0 1 2 3 4 # index
[ 10 , 20, 30, 40, 50 ] # items
Calculate negative index by adding the negative index value to the number of items in the `list`.
(number of items) + (negative index)
5 + (-1)
equals to 5 - 1
equals to 4
Four (4] is the positive (actual) index to reference given the number of items and the negative index was known ahead of time.