How to Remove the Last N Elements of a List in Python
Removing the last
N elements of a list can be tricky at times.
Suppose I have the following list.
lst = [1, 2, 3, 4]
N elements by slicing
Most of us know that we can use
-1 to get the last element of a list. Similar, we can use the slice notation along with negative index to remove the last element.
print(lst[-1]) # 4 print(lst[:-1]) # [1, 2, 3] print(lst) # [1, 2, 3, 4]
Note that this will create a shallow copy of the list. We can remove the last
N element of a list like so:
lst = lst[:-n]
But, this actually does not work when
n == 0 because it results in this operation, which will grab nothing from the list.
print(lst[:-0]) # 
We can circumvent this by slicing with
-n or None, which will evaluate to
n > 0 and
n == 0.
lst = lst[:-n or None]
N elements using
If we don’t want to reassign the list, we can directly modify the original list with
del lst[-1:] print(lst]) # [1, 2, 3]
To remove the last
N elements in a list, we can do the following: