Python Negative indexing


Negative indexing

Python allows negative indexing for its elements in the list where the index of -1 refers to the last item, -2 to the second last item, and so on.

The negative index logic is elementary and straightforward. A negative index is a beneficial concept that enables the user to index an array (or a list in Python’s case) relative to the ending rather than the starting. You can apply a negative index to begin the slicing from the end of the string.
As all of you are familiar with, indexes are used in arrays in every programming language. You can easily access the elements of an array by working through their indexes. Not all programming languages enable the user to use a negative index value. But the Python programming language allows the user to use negative indexing of arrays, something which is not possible in arrays in most other programming languages. It implies that the index value of -1 returns the last element, and -2 provides the second last element of an array. The negative indexing begins from where the array stops. This means that the last element of the array becomes the first element in the negative indexing which is -1.

Here is a list of elements; find its negative index in the List

  • Method #1: index() + len(): You can take the index of the element using index() and subtract it from the list length to obtain the expected result.
  • Method #2: Using ~ operator + list slicing + index(): You can reverse the List by slicing, and use the ~ operator to perceive negation, index() is practiced to obtain the desired negative index.

Example No.1:

b = ['k','n','o','w','l','e','d','g','e'] print(b[-5:-2])

OUTPUT:

['l', 'e', 'd']

Example No.2:

b = ['k','n','o','w','l','e','d','g','e'] print(b[0:9])

OUTPUT:

['k','n','o','w','l','e','d','g','e']