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

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

 

In the previous article we discussed all the methods which used indexing implemented in a more manual way. In this article let’s discuss a few more methods which are much simpler and mostly one liner.

  • Using pop()
  • Using the reverse iterator
  • Using the reverse()
  • Using itemgetter()

 

1. Using pop() method:

This method removes the last element from the list and returns the removed element. There’s no need for indexing in this method.

 

Example:

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

last_element= list.pop()

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

Output:

Note: This method changes the original list by removing the last element.

 

2.Using reversed() and next():

The reversed() method takes in a sequence, here a list as an argument and simply returns the list iterated in reverse order. The next() method returns the next element by accepting an iterator object. Here the next element returned is the last element.

 

Example:

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

iterator_object = reversed(list)
last_element= next(iterator_object)

print("The last element is: ", last_element)
print("Original List;',  list)

Output:

 

We can see that using this method the original list is unaltered.

 

3. Using reverse():

This method doesn’t take in or return any arguments. It just performs in-place reversing of the given list. We can immediately access the last element after reversing, by accessing the first element of the reversed list.

 

Example:

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

list.reverse()
last_element=list[0]

print("The last element is: ", last_element)
print("Original List;', list)

Output:

This method, as the name suggests, changes the original list by reversing its elements’ order.

 

Note: This approach is not so efficient as it eats up time in reversing the given list.

 

4. Using itemgetter():

The itemgetter() method  is one of the many methods present in the operator module. It takes in one or more integers as argument(s) and returns a callable object. This object acts like a special function and can access elements using indexing.

 

In the example below, the operator.itemgetter(-1) part of the code  returns an object which is a function  which gets the last element. We assigned this object a name, get_last_element

To this function we pass our list as an argument and store it in a variable named lastElement 

 

Example:

import operator

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

get_last_elelment = operator.itemgetter(-1)
lastElement = get_last_element(list)

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

Output:

 

This method doesn’t change the original list. It just generates a callable object which accesses elements using indexing.

 

Leave a comment