Remove last element from list python

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.

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.

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.

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

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *