Use the list pop() method or list[-1] slice notation syntax to get the last element of the list in Python. There are also many methods to do it but these methods work well.
Example Last element of the list Python
Simple example code.
Using list pop() method
This method removes and returns the last method from the list.
data = ["infy", "tcs", "affle", "dixon", "astral"] res = data.pop() print(res) print(data)
Using list[-1] syntax
The list[-1] is the most preferable, shortest, and Pythonic way to get the last element. This way given list will not change.
data = ["infy", "tcs", "affle", "dixon", "astral"] res = data[-1] print(res) print(data)
[‘infy’, ‘tcs’, ‘affle’, ‘dixon’, ‘astral’]
Do comment if you have any doubts and suggestions on this Python List topic.
Note: IDE: PyCharm 2021.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.