How to delete the last element in a list in Python

In Python, you can delete the last element in a list using either the "del" statement or the "pop()" method. Let's explore each method with examples:

Using the "del" statement

The "del" statement allows you to remove an element from a list by specifying its index. To delete the last element, you can use the index "-1," which represents the last position in the list.

# Original list my_list = [10, 20, 30, 40, 50] # Deleting the last element using 'del' statement del my_list[-1] print(my_list) # Output: [10, 20, 30, 40]

Using the "pop()" method

The "pop()" method is a list method that removes and returns the element at a specified index. If no index is provided, it automatically removes the last element from the list.

# Original list my_list = [10, 20, 30, 40, 50] # Deleting the last element using 'pop()' method my_list.pop() print(my_list) # Output: [10, 20, 30, 40]

remove last item

Using the slice() operator

def delete_last_element(list): """Deletes the last element in a list.""" new_list = list[:-1] return new_list list = [1, 2, 3, 4, 5] print("Original list:", list) new_list = delete_last_element(list) print("New list:", new_list)

Here is an explanation of how each of these methods works:

  1. The pop() method removes the element at the specified index from the list. If no index is specified, the pop() method removes the last element in the list.
  2. The del statement deletes the element at the specified index from the list. If no index is specified, the del statement deletes the last element in the list.
  3. The slice() operator returns a new list that is a copy of the original list, but with the specified elements removed. In this case, the slice() operator is used to return a new list that is a copy of the original list, but without the last element.

Conclusion

To delete the last item in a list in Python, you can use the "del" statement with the index "-1" or the "pop()" method without any arguments. Both methods effectively remove the last element from the list, adjusting its length accordingly. If you don't need the removed element, using "pop()" without arguments is more convenient, while "del" is a concise option when the deleted value is not required.