Remove last element from list python

Previous
Next

In this post, we will see how to remove the last element from a list in python.


Using list.pop()

You can use list.pop() method to remove the last element from the list.

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:

List Of Countries are: [‘India’, ‘China’, ‘Bhutan’, ‘Nepal’]
List Of Countries after removing last element: [‘India’, ‘China’, ‘Bhutan’]
Removed country: Nepal

pop will raise index error if the list is empty.


Using del statement

You can use del statement to remove last element.

listOfCountries = ['India','China', 'Bhutan','Nepal'] print("List Of Countries are:",listOfCountries) del listOfCountries[-1] print("List Of Countries after removing last element:",listOfCountries)

Output:

List Of Countries are: [‘India’, ‘China’, ‘Bhutan’, ‘ada’]
List Of Countries after removing last element: [‘India’, ‘China’, ‘Bhutan’]

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.

listOfCountries = ['India','China', 'Bhutan','Nepal'] print("List Of Countries are:",listOfCountries) listOfCountries = listOfCountries[:-1] print("List Of Countries after removing last element:",listOfCountries)

Output:

List Of Countries are: [‘India’, ‘China’, ‘Bhutan’, ‘Nepal’]
List Of Countries after removing last element: [‘India’, ‘China’, ‘Bhutan’]

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

Previous
Next

Add Comment