Python

Python List -1 Index

The term “List” refers to a data structure in Python that can contain multiple objects. Each value in a list has an index, which is a number that specifies its position in the specified list. The initial element in a specified list has an index/position of “0”, the next element has an index/position of “1”, etc. The “-1” index is a special index that refers to the last list value.

This post delivers a comprehensive/detailed overview of the Python “List -1 index” using appropriate examples.

What is the Python List -1 Index?

The “-1” index corresponds to the last value in a list. This means that if you have a list with five values, the “-1” index will refer to the last i.e., the “fifth” value.

Example 1: Using Python List -1 Index to Access the Last Value

The following code prints the last value in the list:

list_value = ["Joseph", "Anna", "Lily"]
print(list_value[-1])

 

In the above code, the “list_value[-1]” expression is used to get the last indexed value of the created list “list_value”.

Output

The last value of the specified list has been displayed in this output.

Example 2: Using Python List -1 Index to Remove the Last Value

The code given below is utilized to remove the last list value:

list_value = ["Joseph", "Anna", "Lily"]
print('Given List: ', list_value)
del list_value[-1]
print('After Removing Last Value: ', list_value)

 

In the above code snippet, the “del” statement is used with the “-1” index to remove the last value from the given list.

Output

The last value of the defined list i.e., “Lily” has been deleted successfully.

Example 3: Using Python Negative Indexing to Access Value From the End

This given code uses negative indexing to access the value from the end of the list:

list_value = ["Joseph", "Anna", "Lily"]
print(list_value[-2])

 

In the above code lines, the index “-2” is specified inside the square bracket notations to access the specified element value from the end of the list.

Output

The element present at the specified negative index has been invoked in the above output appropriately.

Note: The “-1” index is a special index, so it’s crucial to be careful while utilizing it. For instance, if we try to access the “-1” index of an empty list, we will get an “IndexError” exception, as follows:

Conclusion

In Python, the List “-1” index shows the usage of negative indexing, which means the last value of the specified list. The Python List “-1” index is a useful tool for accessing and removing the last value in a list. The “-1” index can cause errors if we apply it to an empty list. This post presented a complete guide on the Python “List -1 Index” with multiple examples.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.