How to delete last item in list | Python

There are multiple ways to remove the last element from a list in Python. Here are a few examples:

Using the pop() method:

lst = [1, 2, 3, 4, 5] lst.pop() print(lst)
//Output: [1, 2, 3, 4]
This will remove the last element from the list and print the modified list [1, 2, 3, 4].

Using list slicing:

lst = [1, 2, 3, 4, 5] lst = lst[:-1] print(lst)
//Output: [1, 2, 3, 4]
This will slice the list to exclude the last element and print the modified list [1, 2, 3, 4].

Using the del keyword:

lst = [1, 2, 3, 4, 5] del lst[-1] print(lst)
//Output: [1, 2, 3, 4]
This will delete the last element of the list and print the modified list [1, 2, 3, 4].

Using List Unpacking Technique

lst = [1, 2, 3, 4, 5] *lst, _ = lst print(lst)
//Output: [1, 2, 3, 4]
Here the underscore(_) ignores the last value and finally assigns it to the list.
remove last item
It is important to note that using lst = lst[:-1] does not really remove the last element from the list, but assign the sublist to lst. This makes a difference if you run it inside a function and lst is a parameter. With lst = lst[:-1] the original list (outside the function) is unchanged, with del lst[-1] or lst.pop() the list is changed. Keep in mind that all the above methods will modify the original list. If you want to keep the original list and create a new list, you can use the first two options and assign the result to a new variable or you can use the slicing method and create a new list with the result.