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

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

How to get the last element of a list?

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.

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

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

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

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

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.

 

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

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

 

Leave a comment