In Python, how do you get the last element of a list?
We have many ways of getting the last element of the list:-
The simplest way is to use abc_list[-1]. Let me give you an example that how it works.
abc_list=[1, 2, 3]abc_list[-1]
abc_list=[1, 2, 3]
The same way you can get all the elements till first using this method.
Where n = index of an element from last that you want.
Below is the algorithm to get the first element of the list.
But if your list is empty when you perform this method then you will get indexNotFound Error. So make sure your list is not empty when you are trying to get elements of your list by this method.
The second method to get the last element is to use operator.itemgetter:
import operatorabc_list=[1, 2, 3]last = operator.itemgetter(-1)last(abc_list)
last = operator.itemgetter(-1)
You can also do by list slicing a slice of a list returns a new list so we can slice from -1 to the end if we are going to want the element in a new list:-
abc_list=[1, 2,3]abc_slice = abc_list[-1:]abc_slice
abc_slice = abc_list[-1:]
It has an upper hand that it does not fail if your list is empty. Instead of giving index not found Error like the above method it will return you an empty list.
To know more about this you can have a look at the following video tutorial:-
Certification in Digital Marketing |
Certification in Big Data Analytics |
Certification in Cloud & Devops |
Certification in Full Stack Web Development
Big Data and Data Science Master’s Course |
Data Science Architect Master’s Program |
Cloud and DevOps Architect Master’s Course |
Artificial Intelligence Engineer Master’s Course |
Microsoft Azure Certification Master’s Training
Data Science Course Online |
Big Data Hadoop Certification Training |
Machine Learning Course Online |
Artificial Intelligence Course and Training |
Salesforce Certification Training: Administrator and App Builder |
Tableau Training and Certification Course |
Python Data Science Course & Training |
Ethical Hacking Course |
Business Analyst Course |
Courses in Cyber Security
© COPYRIGHT 2011-2021 INTELLIPAAT.COM. ALL RIGHTS RESERVED.
Download Salary Trends Now !
Learn how professionals like you got up to 100% Salary Hike.