How to get the last element of a list? Part I
How to get the last element of a list?
There are several ways to find the last element of any given list:
- Using negative Indexing
- Using Slicing
- Using Indexing
- Using loops
Let’s discuss each of the above methods in detail.
- Using Negative Indexing:
Negative Indexing is one of the ways of accessing elements of any sequence. It means accessing elements in the reverse order. We just start giving the index -1 from the rightmost end of the sequence.
- Using Indexing:
As discussed, simple Indexing is a way of accessing elements of any sequence. Here we used the len() function which finds the length of the list. Then we give the index as list_length-1.
Note: This method doesn’t alter the elements in the original list.
- Using Slicing:
Slicing is a way to get the sublist of any given list. To know more about slicing in Python, refer to the article below.
The slice notation simply means we start printing the sublist from the rightmost end of the list i.e., index=-1 and as we did not give any stop before value, it prints all the way to the first element.
This method also just accesses the elements of the list without performing any changes to the original list.
- Using loops:
In this approach, we iterate through the length of the list using the len() function which is put in a for loop, and using len(list)-1 we access the last element in the list.
This method also doesn’t alter the elements in the original list.