Python list first to second last

This post will discuss how to remove the last element from a list in Python.

1. Using list.pop() function

The simplest approach is to use the lists pop([i]) function, which removes an element present at the specified position in the list. If we dont specify any index, pop() removes and returns the last element in the list.

1
2
3
4
5
6
7
if __name__ == '__main__':
l = list(range(1, 5))
print(l)# [1, 2, 3, 4]
l.pop()
print(l)# [1, 2, 3]

DownloadRun Code


The pop([i]) function raises an IndexError if the list is empty as it tries to pop from an empty list.

2. Using Slicing

We know that lists can be sliced in Python. We can use slicing to remove the last element from a list. The idea is to obtain a sublist containing all elements of the list except the last one. Since slice operation returns a new list, we have to assign the new list to the original list. 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].

1
2
3
4
5
6
7
if __name__ == '__main__':
l = list(range(1, 5))
print(l)# [1, 2, 3, 4]
l = l[:-1]
print(l)# [1, 2, 3]

DownloadRun Code


Note that this function doesnt raise any error on an empty list but constructs a copy of the list, which is not recommended.

3. Using del statement

Another way to remove an element from a list using its index is the del statement. It differs from the pop() function as it does not return the removed element. Unlike the slicing function, this doesnt create a new list.

1
2
3
4
5
6
7
if __name__ == '__main__':
l = list(range(1, 5))
print(l)# [1, 2, 3, 4]
del l[-1]
print(l)# [1, 2, 3]

DownloadRun Code


The above code raises an IndexError if the list is empty since it tries to access an index of the list which is out of range.

Thats all about removing the last element from a list in Python.

Video liên quan

Chủ đề