AppDividend
Latest Code Tutorials

How to Get Last Element of a List in Python

To get Python last element in list:

  1. Using list[-1] syntax and I am assuming that you have a non-empty list.
  2. Using list.pop() method.

Python last element in list

To get the last element of the list in Python, use the list[-1] syntax. The list[-n] syntax gets the nth-to-last element. So list[-1] gets the last element, and list[-2] gets the second to last. The list[-1] is the most preferable, shortest, and Pythonic way to get the last element.

To create a list in Python, use the square brackets([ ]) and add the elements in the list separated by commas.

data = ["infy", "tcs", "affle", "dixon", "astral"]

In this list, the “astral” element is the last item; to access that element, write the following code.

last_element = data[-1]

What this code will do is it will pluck the last element and store it into the last_element, and we can print the element using the print() function.

data = ["infy", "tcs", "affle", "dixon", "astral"] 

last_element = data[-1]
print(last_element)

Output

astral

IndexError in Python List

If the expected item does not exist, it will throw an IndexError. This means that list[-1] will raise an exception if the list is empty because an empty list can’t have the last element.

data = [] 

last_element = data[-1]
print(last_element)

Output

Traceback (most recent call last):
  File "/Users/krunal/Desktop/code/pyt/database/app.py", line 3, in <module>
    last_element = data[-1]
IndexError: list index out of range

As you can see that we got: IndexError: list index out of range

Using list.pop() Method

The list.pop() in the Python method removes and returns the object at the given index (passed as an argument) from a list.

data = ["infy", "tcs", "affle", "dixon", "astral"] 

last_element = data.pop()
print(last_element)

Output

astral

That is it for this tutorial.

Related posts

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.