In this post, we will see how to remove the last element from a list in python.
Table of Contents
Using list.pop()
You can use list.pop() method to remove the last element from the list.
1 2 3 4 5 6 7 |
listOfCountries = ['India','China', 'Bhutan','Nepal'] print("List Of Countries are:",listOfCountries) removedCountry = listOfCountries.pop() print("List Of Countries after removing last element:",listOfCountries) print("Removed country:",removedCountry) |
Output:
pop will raise index error if the list is empty.
Using del statement
You can use del statement to remove last element.
1 2 3 4 5 6 |
listOfCountries = ['India','China', 'Bhutan','Nepal'] print("List Of Countries are:",listOfCountries) del listOfCountries[-1] print("List Of Countries after removing last element:",listOfCountries) |
Output:
Please note that list.pop() returns the remove element, but del statement does not return the removed element.
It raises IndexError if list is empty as it is trying to access an index that is out of range.
Using slicing
We can also use slicing to remove the last element. We can get a sublist of elements except the last element.
1 2 3 4 5 6 |
listOfCountries = ['India','China', 'Bhutan','Nepal'] print("List Of Countries are:",listOfCountries) listOfCountries = listOfCountries[:-1] print("List Of Countries after removing last element:",listOfCountries) |
Output:
Please note that slicing operation will return a new list, so this method is not recommended. You can obviously assign the list to the old one.
It does not throw index error in case the list is empty but creates a copy of the list.
That’s all about how to remove last element from list in python