/  Technology   /  How to get the last element of a list in Python? Part I
How to get the last element of a list in Python?

How to get the last element of a list in Python? Part I

 

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.

 

  1. 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.

 

Example:

list= [2,4,6,8,10]

last_element= list[-1]

print("Last element is: ", last_element)
print("Original List:", list)

Output:

 

  1. 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. 

 

Example:

list= [2,4,6,8,10]

last_element= list[len(list)-1]

print("Last element is: ", last_element)
print("Original List:", list)

Output:

Note: This method doesn’t alter the elements in the original list.

 

  1. 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 Slicing

 

Example:

list= [2,4,6,8,10]

last_lelment= list[-1:]

print("Last element is: ", last_elelment)
print("Original List:", list)

Output:

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.

 

  1. 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.

 

Example:

list= [2,4,6,8,10]

for i in range(0, len(list)):
   if i == (len(list0-1) :
      lastElement = list[i]

print("Last element:", listElement)
print("Original List:", list)

Output:

 

This method also doesn’t alter the elements in the original list.

Leave a comment