What is negative index in Python?
Negative indexes are a way to allow you to index into a list, tuple or other indexable container relative to the end of the container, rather than the start.
They are used because they are more efficient and are considered by much more readable.
- >>> l = [0,1,2,3,4,5]
- >>> l[-1]
- 5
- >>> l[len(l) - 1]
- 5
line 2 and line 4 are functionally equivalent, but line 2 will be significantly quicker.
You can also use negative indexes in slices, and as with positive indexes, when you do a slice operation, the last element is not included in the slice
- >>> l = [0,1,2,3,4,5]
- >>> l[-3:-1]
- [3,4]
As with positive indexes the length of a slice can be calculated by subtracting the start index from the end index - in this case: [math]-1 - (-3) = -1 + 3 = 2[/math] as demonstrated.
you can even use negative indexes with negative steps to make a reversed slice :
- >>> l = [0,1,2,3,4,5]
- >>> l[-1:-4:-1]
- [5,4,3]
here the 3rd value in the slice tells Python to go backwards from index -1 (the last element - number 5 here) to index -4 (i.e. 4th from the end - item 2 here), with the final element in the slice omitted.
Articoli simili
- Quale cuffia VR fornirà la migliore esperienza VR: Oculus Rift, HTC Vive Pro, Valve Index o Pimax 5K Plus?
- Cuffie VR: HTC Veve, Valve Index e la gamma Oculus; qual è il migliore, tenendo conto della qualità e del rapporto qualità-prezzo?
- Quali sono le cose negative di TikTok?
- Perché il Pixel 3 sta ricevendo recensioni così negative?