Tutorial Example

Python Get Last Item in List: A Completed Guide – Python Tutorial

Python list can contain some items in its structure, which is very useful for us to save data. How to get the last item in the python list? In this tutorial, we will use some examples to discuss this topic.

Method 1: use list.pop() function

Here is an example:

data_list = [1, 2, 3, 4, 5]

last_item = data_list .pop()
print(last_item)
print(data)

Run this code, we will get the last item in list data_list is: 5.

5
[1, 2, 3, 4]

However, we will also find the data in data_list is changed. The length of python list is shorted.

Method 2: use -1 index

Here is an example code.

data_list = [1, 2, 3, 4, 5]

print(data_list[-1])
print(data_list)

Run this code, you will get the result:

5
[1, 2, 3, 4, 5]

From the result we can find: we can get the last item in data_list by -1 index. Meanwhile, the length of data_list is not changed.

Method 3: use the index of last item

We can find the index of the last item in list, then get it. Here is an example code.

data_list = [1, 2, 3, 4, 5]

lenth = len(data_list)
print(data_list[lenth-1])
print(data_list)

Run this code, we will get the result:

5
[1, 2, 3, 4, 5]

This code also works fine.

To summary, the method 2 is the best choice, it can get the last item in python list and it also do not change the data in list.