Indexing is a general term in programming that refers to accessing individual elements of a sequence like an array, list, or string by their position.
In this article, we will talk about negative indexing and index -1 in Python.
What is negative indexing in Python?
Negative indexing lets you access list items or sequence items from the end.
The positive indexing works from the left to right side of the sequence, and the negative indexing starts from the right to left of the sequence.
The index -1 is negative indexing.
Negative indices can be helpful when you don’t know the length of the list and have to access the last few elements.
sample_list = [11, 28, 19, 21, 46] print(sample_list[-3:])
To get the last three elements of the list, we used list slicing and passed the negative index and colon operator.
The [-3:] means return the last three elements of the list.
Python index -1
Python index -1 refers to the last element of the list or string, or array. So, for example, if you have a list num = [1, 2, 3], then num[-1] will return the element “3” because it’s the last element.
The list index starts with 0 and goes up to its length.
To access the last element of the list, use the index -1, called negative indexing.
num = [111, 119, 121, 146] last_element = num[-1] print(last_element)
The last element of the list is “146,” and that’s why the index -1 returns the “146” as an output.
That’s it for this tutorial.