3 Examples to Get Last Element of A List In Python 3

Table of Contents

A list is a collection of arbitrary objects, somewhat akin to an array in many other programming languages but more flexible.

Lists are defined in Python by enclosing a comma-separated sequence of objects in square brackets ([]).

we have 3 ways to get the last element of the list in Python.

  • Using list[-1] syntax
  • Using list.pop() method
  • Using list indexing

Let’s see these approaches one by one.

Using list[-1] syntax to list last element

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, 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 items in the list separated by commas.

>>> data = []
>>> for i in range(10):
… data.append(i)

or
data = list(range(0, 10))

>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In this list, the 9 element is the last item, and to access that element, write the following code.

last_element = data[-1]

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

last_element = data[-1]
print(last_element)
Output
9

 

Using list.pop() Method to get the last item

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

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

last_element = data.pop()
print(last_element)
Output
9

Now data=[0, 1, 2, 3, 4, 5, 6, 7, 8]

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.

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

# get element at index position size-1

last_elem = data[len(data) – 1]

print(‘Last Element: ‘, last_elem)

IndexError in Python List

If the expected item does not exist, then 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 we can see that we got: IndexError: list index out of range

Table of Contents

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

You might also like