Python get last element from list

In this tutorial, I show you how to get the last element of the list in Python. This is a very common scenario when you manipulate any list in python.

 

Python get last element from list

 

There are two ways in python to get the last element from the list –

  1. The popular way using the list[-1] method.
  2. The list.Pop() method.

Let’s understand this method one by one with code examples –

 

  1. Python list[-1] method to get the last element from the list.

The list [-1] method gets the last element from the list and the list [-2] gets the second last element from the list. Suppose you have the below list that has some elements now you want to get the last element.

Example 1-

testlist = [1, 2, 3]
testlist[-1]
print(testlist)

Output –

3

 

The “-1” index is used to get the last element from the list.

Note – The above code throws an exception if the list is blank or empty because you try to get the element that does not exist and the code will throw the index out the range exception. See below example where I have used empty list –

Example 2 –

//Empty python list
testlist = []
print(testlist[-1])

Output –

File "script.py", line 4, in <module>
print(testlist[-1])
IndexError: list index out of range

 

Let understand the with one more example –

 

Example 2-

if __name__ == '__main__':
  testlist = list(range(1, 5))
   print(testlist[-1])
   print(testlist[len(testlist)-1])

Output 

4
4

Both the print statement return “4” the first where I passed “-1” directly to get the last element from the list and the second first I get the length of the list then “-1” from the length.

 

  1. The list.pop() method

This is the alternate method to get the last element from the list in python. The list.pop() method pops/remove and returns the element from the list.

Example 1 –

testlist = ["United States", "India", "UK", "Australia", "France"]
last_element = testlist.pop()
print(last_element)

Output –

France

If you don’t want to modify the actual list kindly use the list[-1] method because the pop() method removes the element from the list.

Conclusion

These are the two ways to manipulate the list in python and this is how you get the last element from the list in python.

Leave a Reply

Your email address will not be published. Required fields are marked *