Last value of array python

6 ways to get the last element of a list in Python

In this article, we will discuss six different ways to get the last element of a list in python.

Get last item of a list using negative indexing

List in python supports negative indexing. So, if we have a list of size “S”, then to access the Nth element from last we can use the index “-N”. Let’s understand by an example,
Suppose we have a list of size 10,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

To access the last element i.e. element at index 9 we can use the index -1,

# Get last element by accessing element at index -1 last_elem = sample_list[-1] print('Last Element: ', last_elem)

Similarly, to access the second last element i.e. at index 8 we can use the index -2.

Frequently Asked:

Using negative indexing, you can select elements from the end of list, it is a very efficient solution even if you list is of very large size. Also, this is the most simplest and most used solution to get the last element of list. Let’s discuss some other ways,

Get last item of a list using list.pop()

In python, list class provides a function pop(),

It accepts an optional argument i.e. an index position and removes the item at the given index position and returns that. Whereas, if no argument is provided in the pop() function, then the default value of index is considered as -1. It means if the pop() function is called without any argument then it removes the last item of list and returns that.

Let’s use this to remove and get the last item of the list,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Remove and returns the last item of list last_elem = sample_list.pop() print('Last Element: ', last_elem)

The main difference between this approach and previous one is that, in addition to returning the last element of list, it also removes that from the list.

Get last item of a list by slicing

We can slice the end of list and then select first item from it,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Get a Slice of list, that contains only last item and select that item last_elem = sample_list[-1:][0] print('Last Element: ', last_elem)

We created a slice of list that contains only the last item of list and then we selected the first item from that sliced list. It gives us the last item of list. Although it is the most inefficient approach, it is always good to know different options.

Читайте также:  Плагины для html vscode

Get last item of a list using itemgetter

Python’s operator module provides a function,

It returns a callable object that fetches items from its operand using the operand’s __getitem__() method. Let’s use this to get the last item of list by passing list as an operand and index position -1 as item to be fetched.

import operator sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = operator.itemgetter(-1)(sample_list) print('Last Element: ', last_elem)

It gives us the last item of list.

Get last item of a list through Reverse Iterator

In this solution we are going to use two built-in functions,

  1. reversed() function : It accepts a sequence and returns a Reverse Iterator of that sequence.
  2. next() function: It accepts an iterator and returns the next item from the iterator.

So, let’s use both the reversed() and next() function to get the last item of a list,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get Reverse Iterator and fetch first element from reverse direction last_elem = next(reversed(sample_list), None) print('Last Element: ', last_elem)

It gives us the last item of list.
How did it work?
By calling the reversed() function we got a Reverse Iterator and then we passed this Reverse Iterator to the next() function. Which returned the next item from the iterator.
As it was a Reverse Iterator of our list sequence, so it returned the first item in reverse order i.e. last element of the list.

Get last item of a list by indexing

As the indexing in a list starts from 0th index. So, if our list is of size S, then we can get the last element of list by selecting item at index position S-1.
Let’s understand this by an example,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get element at index position size-1 last_elem = sample_list[len(sample_list) - 1] print('Last Element: ', last_elem)

It gives us the last item of list.

Using the len() function we got the size of the list and then by selecting the item at index position size-1, we fetched the last item of the list.

So, here we discussed 6 different ways to fetch the last element of a list, although first solution is the simplest, efficient and most used solution. But it is always good to know other options, it gives you exposure to different features of language. It might be possible that in future, you might encounter any situation where you need to use something else, like in 2nd example we deleted the last element too after fetching its value.

The Complete example is as follows,

import operator def main(): print('*** Get last item of a list using negative indexing ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Get last element by accessing element at index -1 last_elem = sample_list[-1] print('Last Element: ', last_elem) print('*** Get last item of a list using list.pop() ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Remove and returns the last item of list last_elem = sample_list.pop() print('Last Element: ', last_elem) print('*** Get last item of a list by slicing ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = sample_list[-1:][0] print('Last Element: ', last_elem) print('*** Get last item of a list using itemgetter ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = operator.itemgetter(-1)(sample_list) print('Last Element: ', last_elem) print('*** Get last item of a list through Reverse Iterator ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get Reverse Iterator and fetch first element from reverse direction last_elem = next(reversed(sample_list), None) print('Last Element: ', last_elem) print("*** Get last item of a list by indexing ***") sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get element at index position size-1 last_elem = sample_list[len(sample_list) - 1] print('Last Element: ', last_elem) if __name__ == '__main__': main()
*** Get last item of a list using negative indexing *** Last Element: 9 *** Get last item of a list using list.pop() *** Last Element: 9 *** Get last item of a list by slicing *** Last Element: 9 *** Get last item of a list using itemgetter *** Last Element: 9 *** Get last item of a list through Reverse Iterator *** Last Element: 9 *** Get last item of a list by indexing *** Last Element: 9

Источник

Читайте также:  Add method in set java

How to Get the Last Element of a List In Python

In this tutorial, let us look at the most efficient ways to find the last element in list in Python.

What is a List in Python?

The list is one of the most commonly used data types in Python. A list is a collection of elements that can be of any data type. A single list can contain a combination of numbers, strings, nested lists, etc.

How to Get the Last Element of a List in Python

Method 1 – By Iterating all the elements in a list

The most common and straightforward way to get last element in list is through iterating the entire element till it reaches the last element, as shown below.

# Python code to access the last element # in a list using for loop # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) # using loop method to print last element for i in range(0, len(number_list)): if i == (len(number_list)-1): print ("The last element of list is : "+ str(number_list[i])) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list is : 6

Method 2 – Using the reverse() method

The reverse() method in Python is used to reverse the elements of a list. The reverse() method does not take any arguments and does not return any values instead, it reverses the existing list.

# Python code to access the last element # in a list using reverse() method # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) # using reverse method to print last element number_list.reverse() print("The last element of list using reverse method are : " + str(number_list[0])) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using reverse method are : 6

Method 3 – Using pop() method

The pop() method is used to access the last element of the list and returns the removed item. The pop() method accepts an integer as the argument, which is basically the index of the item which needs to be removed from the list.

Читайте также:  Text overflow css style

Example – list.pop(0) will remove and return the first element in the list.

Note – Calling the pop() method will remove the last item from the list itself. Hence if you are re-using the list, this approach is not recommended as the element is removed.

# Python code to access the last element # in a list using pop() method # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) # using pop() method to print last element print("The last element of list using reverse method are : " + str(number_list.pop())) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using reverse method are : 6

Method 4 – Using Negative Indexing [] Operator

The negative index is the way of indexing the element from the end of the list with an index starting from -1, i.e., -1 gives the last element, -2 gives the last 2nd element, and so on.

The major use of negative indexing can be used to reverse a list without using any built-in function.

You can also find the last element in the list using length-1. In order to access the last element, we need to know the length of the list.

# Python code to access the last element # in a list using negative indexing # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) # using length-1 to print last element print("The last element of list using length-1 method are : " + str(number_list[len(number_list) -1])) # using [] operator to print last element print("The last element of list using reverse method are : " + str(number_list[-1])) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using length-1 method are : 6 The last element of list using reverse method are : 6

Method 5 – Using itemgetter()

The operator module in Python has vast features to perform all mathematical, logical, comparison operations.

The itemgetter() method is one of the methods in the operator module, and it accepts one or more integer arguments and returns the callable object.

import operator # Python code to access the last element # in a list using itemgetter() method # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) getLastElement = operator.itemgetter(-1) # using [] operator to print last element print("The last element of list using reverse method are : " + str(getLastElement(number_list))) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using reverse method are : 6

Источник

Оцените статью