There are multiple ways to Remove the last element from the list in Python. The simplest approach is to use the list’s pop([i])
function, which removes an element present at the specified position in the list.
Remove the last element from the list of Python
Simple example code.
Using list.pop()
function
The pop([i])
function raises an IndexError
if the list is empty as it tries to pop from an empty list.
list1 = [1, 2, 3, 4, 5]
print("Original list: " + str(list1))
ele = list1.pop()
print("Updated list: " + str(list1))
Using Slicing
This can be done using the expression l = l[:-1]
, where l
is your list. l[:-1]
is short for l[0:len(l)-1]
.
# slice the list
# from index 0 to -1
list1 = list1[ : -1]
Using del
statement
The del operator removes the item or an element at the specified index location from the list, but the removed item is not returned, as it is with the pop() method.
# call del operator
del list[-1]
Output:
The most efficient way to remove the last element of the list?
Answer: As mentioned in the Python wiki. Time complexities are as follows:
- Pop last
O(1)
- Delete Item
O(n)
- Set Slice
O(k+n)
Let’s see the example
import time
all_t = 0.
for i in range(1000):
list_ = [i for i in range(100000)]
start_ = time.time()
list_.pop()
all_t += time.time() - start_
print("Average Time for POP is {}".format(all_t/1000.))
all_t = 0.
for i in range(1000):
list_ = [i for i in range(100000)]
start_ = time.time()
del list_[-1]
all_t += time.time() - start_
print("Average Time for DEL is {}".format(all_t/1000.))
all_t = 0.
for i in range(1000):
list_ = [i for i in range(100000)]
start_ = time.time()
list_ = list_[:-1]
all_t += time.time() - start_
print("Average Time for SLICE is {}".format(all_t/1000.))
Results
Average Time for POP is 7.793903350830078e-07
Average Time for DEL is 9.80854034423828e-07
Average Time for SLICE is 0.0006206443309783935
So pop()
is the fastest when you do not specify an index.
Source: stackoverflow.com
Comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.