Remove Last Element from List in Python
Given a list, the task is to write a Python program to remove the last element present in the list and update the original list in Python.
Example:
Input: [“geeks”, “for”, “geeks”]
Output:[“geeks”, “for”]
Input: [1, 2, 3, 4, 5]
Output:[1, 2, 3, 4]
Explanation: Here simply we have to remove the last element present in the list and print the resultant list.
Method 1: Remove Last Element from List Using pop() method
First, we create a list li and call the pop() methods which remove the last element from the list.
Python3
li = ["Geeks", "For", "Geeks"]print("Original list: ", li) # call the pop function# ele stores the last element# popped ("Geeks" in this case)ele = li.pop() # print the updated listprint("New list : ", li) |
Output:
Original list: ['Geeks', 'For', 'Geeks'] New list : ['Geeks', 'For']
Method 2: Remove Last Element from List Using Slicing Technique
The slicing technique can also remove the last element from the list. list[:-1] will remove the last element except for all elements.
Python3
# program to delete the last element from the listlist = ["Geeks", "For", "Geeks"]print("Original list: ",list) # slicing the listlist= list[:-1] # print the updated listprint("New list: ",list) |
Output:
Original list: ['Geeks', 'For', 'Geeks'] New list: ['Geeks', 'For']
Method 3: Remove Last Element from List Using del operator
del operator can delete the last element from the list along with index.
Python3
# program to delete the last element from the listlist = ["Geeks", "For", "Geeks"]print("Original list: ",list) # using the del operatordel list[-1] # print the updated listprint("New list: ",list) |
Output:
Original list: ['Geeks', 'For', 'Geeks'] New list: ['Geeks', 'For']
Method 4: Remove Last Element from List Unpacking Technique
Python3
li = ["Geeks", "For", "Geeks"]print(*li)*li, _ = liprint(li) |
Output:
Geeks For Geeks ['Geeks', 'For']
Explanation:
Here we have the star(*) operator that unpacks the sequence or iterables into positional arguments. And then underscore(_) ignores the last value and finally assigns it to the list.
Note:
del and pop are similar but the only difference is, in del the removed element is not returned whereas it is done in pop method.
Conclusion,
Here we have seen some of the possible methods of removing the last element from the list, we can also get some more methods like reversing the array and removing the first character and so on but here also the concept is same.





Please Login to comment...