What Means a Negative List Index in Python? (2 Examples)
Hi! This short tutorial will explain what a negative list index is in the Python programming language.
A negative list index simply means indexing from the end. While Python lists are typically indexed from the front, i.e., from 0, it is also possible to index them from the rear. Let’s see how in this tutorial!
The table of content is structured as follows:
Let’s get right into Python code!
Create Sample Python List
Here, we will create a sample Python list which will be used to demonstrate negative list indexing in Python. So, in your preferred Python IDE, run the line of code below to create the sample list:
my_list = [1,2,3,4,5,6,7,8,9] print(my_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 1: Index List from the End Using Minus Operator
In this first example, we will index the sample list from the end using the minus operator:
k = 1 print(my_list[-k]) # 9
In the example above, “k” stands for the index position of the list element that we want to return. Adding
- to k in
my_list[-k] means that we want to return the first element in the list from the end, which is 9 in this case.
If we change the value of k to 2, the code will output 8, which is the second element in the list from the left. You can play around with the value of k to see what other elements are returned.
Example 2: Index List from the End Using Slicing
In this second example, we are going to index the sample list from the end using slicing:
k = -3 print(my_list[k:]) # [7, 8, 9]
In the above code, we set k to -3 and applied the slicing operator
my_list[-k:] to get the last three elements in a list. You can change the value of k to see what other list elements are returned.
With that, we have demonstrated, with examples, what a negative list index is in Python. I do hope you found this tutorial helpful!
Video, Further Resources & Summary
Do you need more explanations on negative list indexing in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
In the video, we explain in some more detail what a negative list index is in Python.
The YouTube video will be added soon.
Furthermore, I encourage you to check out other interesting Python list tutorials on Statistics Globe, starting with these ones:
- Convert List to Matrix & Vice-Versa in Python (Examples)
- count() Method for Lists in Python (2 Examples)
- Learn Python Programming
- Change Index of Element in List in Python (Example)
- Convert List of Tuples to List of Lists in Python (3 Examples)
This post has shown what a negative list index is in Python. In case you have further questions, you may leave a comment below.
This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.
Statistics Globe Newsletter