Use the pop() method to Get the last element of the list in Python. This is used to access the last element of the list. Or
some_list[-1] is the shortest and most Pythonic.
last_elem = alist.pop()
Note: the pop() method will delete the last element.
Get the last element of the list Python
A simple example code gets the last element.
list1 = [1, 2, 3, 4, 5] ele = list1.pop() print(ele) print("Updated list: " + str(list1)) # another way a_list = ['zero', 'one', 'two', 'three'] print(a_list[-1]) print(a_list)
li[-1] is the fastest and more Pythonic way to do it.
You can do li[-n] to get the nth element starting from the end, it is just access by index and it is in fact faster than li[len(li) – 1].
If you have a list in python the length is given so li works the same way as li[-1].
Do comment if you have any doubts or suggestions on this Pytho list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.