Python is an advanced programming language with dynamic semantics and is used for developing applications, writing scripts, data analysis, machine learning, etc.
Negative indexing is used in Python to manipulate sequence objects such as lists, arrays, strings, etc. Negative indexing retrieves elements from the end by providing negative numbers as sequence indexes.
Below is a diagram that represents how negative indexing is used on a list of 5 elements (30, 45, 20, 15, 60).
To select numbers from the end of the list, we use negative indexes starting from -1 and adding -1 each time to get the next number from the end.
In the example above, to select the element 60 that is placed at the end of the list, we can use the index -1. For element 15, we can use the index -2 and so on.
Note: Negative indexes start from index number -1, while positive indexes start from index number 0.
we can see the same example implemented in the code block below.
list = [30, 45, 20, 15, 60]# get legnth of listsizeOfList = len(list)print(sizeOfList)# print the list using negative inedexesend = (sizeOfList * -1) - 1start = -1for i in range(start, end, -1):# print each element using negative indexesprint("list[{}] = {}".format(i, list[i]))
Below we can see an explanation of the code above:
Line 1: We initialize our list that contains 5 elements.
Line 4: Here, we use the len()
function to get the list size.
Line 9: We get the ending negative index of the list using the formula (sizeOfList * -1) - 1
. We convert the sizeOfList
variable to a negative number (-5) by multiplying it by -1 and adding -1 to iterate till -6 because -6 is not included in Python's range function.
Lines 9–11: We use a for
loop to iterate over the list using negative indexes using i
values from -1 to -5 with an increment of -1 per run.
We can access individual characters in a string using negative indexes. Negative indexes count from the end of the string (-1 for the last character).
word = "Educative"print(word[0]) # Output: 'E'print(word[-1]) # Output: 'e'
Easier list manipulation: With the help of negative indexes, we do not need to know the exact size of the sequence objects to retrieve elements placed at the end of the list.
Simplified code: Using negative indexes, we save on extensive complex code to retrieve the sequence objects' size.
Free Resources