QNA > W > What Is Negative Index In Python?

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.

  1. >>> l = [0,1,2,3,4,5] 
  2. >>> l[-1] 
  3. >>> l[len(l) - 1] 

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

  1. >>> l = [0,1,2,3,4,5] 
  2. >>> l[-3:-1] 
  3. [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 :

  1. >>> l = [0,1,2,3,4,5] 
  2. >>> l[-1:-4:-1] 
  3. [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.

Di Gish

Come possiamo convertire un array 1-dimensionale in un array 2-dimensionale in Python? :: Gli array Python iniziano da 0?
Link utili