The Wayback Machine - https://web.archive.org/web/20240717024524/https://www.geeksforgeeks.org/python-how-to-get-the-last-element-of-list/
Open In App

Python | How to get the last element of list

Last Updated : 18 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Getting the last element of the list is tricky while tracking each element, here we will discuss multiple methods to get the last element of the list. So we have given a list n, Our task is to get the last element of the list using Python.

Example:

Input: [1, 2, 3, 4, 5, 5]
Output: 5
Input: ["Hello", "World"]
Output: World

Explanation: In both of the outputs we are getting the last value of present in the list.

How to get the last element of a list

Approaches to get the last element of the list:

Get the last item of a list using the Reverse Iterator

To get the last element of the list using the naive method in Python. There can be 2-naive methods to get the last element of the list. Iterating the whole list and getting, the second last element and reversing the list, and printing the first element.

Python3




# initializing list
test_list = [1, 4, 5, 6, 3, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using loop method to print last element
for i in range(0, len(test_list)):
 
    if i == (len(test_list)-1):
        print("The last element of list using loop : "
              + str(test_list[i]))
 
# using reverse method to print last element
test_list.reverse()
print("The last element of list using reverse : "
      + str(test_list[0]))


Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element of list using loop : 5
The last element of list using reverse : 5

Get the last item of a list using Negative Indexing

To get last element of the list using the [] operator, the last element can be assessed easily if no. of elements in the list are already known. There is 2 indexing in Python that points to the last element in the list.

  • list[ len – 1 ] : This statement returns the last index if the list.
  • list[-1] : Negative indexing starts from the end.

Python3




# initializing list
test_list = [1, 4, 5, 6, 3, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using len - 1 index to print last list element
print("The last element using [ len -1 ] is : "
      + str(test_list[len(test_list) - 1]))
 
# using -1 index to print last list element
print("The last element using [ -1 ] is : "
      + str(test_list[-1]))


Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element using [ len -1 ] is : 5
The last element using [ -1 ] is : 5

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

To get the last element of the list using list.pop(), the list.pop() method is used to access the last element of the list. The drawback of this approach is that it also deletes the list’s last element, hence is only encouraged to use when the list is not to be reused. 

Python3




# initializing list
test_list = [1, 4, 5, 6, 3, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using pop() to print last list element
print("The last element using pop() is : "
      + str(test_list.pop()))


Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element using pop() is : 5

Get the last item of a list using reversed() with next() 

To get the last element of the list using reversed() + next(), the reversed() coupled with next() can easily be used to get the last element, as, like one of the naive methods, the reversed method returns the reversed ordering of list as an iterator, and next() method prints the next element, in this case, last element. 

Python3




# initializing list
test_list = [1, 4, 5, 6, 3, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using reversed() + next() to print last element
print("The last element using reversed() + next() is : "
      + str(next(reversed(test_list))))


Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element using reversed() + next() is : 5

Get the last item of a list by slicing

In this example, we will use list slicing to get the last element from the list.

Python3




# initializing list
test_list = [1, 4, 5, 6, 3, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
li = last_elem = test_list[-1:][0]
 
# using slicing to print last element
print("The last element using slicing is : ", li)


Output:

The original list is : [1, 4, 5, 6, 3, 5]
The last element using slicing is : 5

Get the last item of a list using itemgetter

The itemgetter can be used instead of lambda functions.  In terms of performance over time, itemgetter is better than lambda functions. When accessing many values, it appears more concise than lambda functions. Here, we will use itemgetter to get out the last element in the list.

Python3




import operator
 
# initializing list
test_list = [1, 4, 5, 6, 3, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
li = last_elem = operator.itemgetter(-1)(test_list)
 
# using itemgetter to print last element
print("The last element using itemgetter is : ", li)


Output:

The original list is : [1, 4, 5, 6, 3, 5]
The last element using itemgetter is : 5

Get the last item of a list using deque from the collections module

Convert the given list to a deque object. Use the pop() method to remove and return the last element of the deque object.Return the popped element as the result.

Python3




from collections import deque
 
# initializing list
test_list = [1, 4, 5, 6, 3, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using deque and pop method to print last list element
last_elem = deque(test_list).pop()
print("The last element using deque is : " + str(last_elem))


Output

The original list is : [1, 4, 5, 6, 3, 5]
The last element using deque is : 5

The above code returns the last element of the given list using the deque.pop() method from the collections module.

Time Complexity: The time complexity of this approach is O(1) since the pop() operation on deque takes constant time.
Space Complexity: space complexity is O(n) since the deque object is created to store the list elements.



Similar Reads

Remove Last Element from List in Python
Given a list, the task is to write a Python program to remove the last element present in the list and update the original list in Python. Example: Input: ["geeks", "for", "geeks"]Output:["geeks", "for"] Input: [1, 2, 3, 4, 5]Output:[1, 2, 3, 4] Explanation: Here simply we have to remove the last element present in the list and print the resultant
4 min read
How to get the first and last elements of Deque in Python?
Deque is a Double Ended Queue which is implemented using the collections module in Python. Let us see how can we get the first and the last value in a Deque. Method 1: Accessing the elements by their index. The deque data structure from the collections module does not have a peek method, but similar results can be achieved by fetching the elements
2 min read
Get last n records of a Pandas DataFrame
Let's discuss how to get last n records of a Pandas DAtaframe. There can be various methods to get the last n records of a Pandas DataFrame. Lets first make a dataframe:Example: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Go
2 min read
Access Index of Last Element in pandas DataFrame in Python
In this article, we are going to see how to access an index of the last element in the pandas Dataframe. To achieve this, we can use Dataframe.iloc, Dataframe.iget, and Dataframe.index. let's go through all of them one by one. Dataframe.iloc - Pandas Dataframe.iloc is used to retrieve data by specifying its index. In python negative index starts fr
3 min read
Python - Remove last element from dictionary
Given a dictionary, the task is to remove the last occurring element, i.e. the last key-value pair in the dictionary. Example: Input: {1: 'Geeks', 2: 'For', 3: 'Geeks'} Output:{1: 'Geeks', 2: 'For'}Method 1: Using popitem() method Python dictionary popitem() method removes one key, value pair as a two-item tuple and modifies the removes the last ke
5 min read
Python | Insert Nth element to Kth element in other list
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter-list shifts of elements. Having a solution to this problem is always very useful. Let’s discuss the certain way in which this task can be performed. Method 1: Using pop() + insert() + index() This particular task can be performed using a combinat
9 min read
How to access the last element in a Pandas series?
Prerequisite: Pandas Pandas series is useful in handling various analytical operations independently or as being a part of pandas data frame. So it is important for us to know how various operations are performed in pandas series. The following article discusses various ways in which last element of a pandas series can be retrieved. Method 1: Naive
3 min read
Python | Subtract two list elements if element in first list is greater
Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5,
5 min read
How to get GET request values in Django?
Django, a high-level Python web framework, simplifies the process of web development. One common task in web applications is handling GET requests, which are typically used to retrieve data from a server. In this article, we'll create a small Django project that displays a message using data from a GET request. How to get GET request values in Djan
2 min read
How to get the address for an element in Python array?
In this article we are going to discuss about getting the address of an particular element in the Python array. In python we can create the array using numpy. Numpy stands for numeric python used to create and process arrays. We have to import numpy module import numpy as np Syntax to create array: np.ndarray([element1,element2,....,element n]) Met
3 min read
Practice Tags :
three90RightbarBannerImg