Python List without Last Element
Get Python List without Last Element
There are many ways to get given Python List without last element, based on whether you would like to preserve the original list.
You can use slicing to slice away the last element and get a new copy of the list without last element.
Or, you can use list.pop() method to remove the last element of the list. But remember, this operation modifies the original list.
So, based on the requirement, you may choose one of the above two approaches to get the list without last element.
1. List without last element using Slicing
The syntax to get the list without last element using slicing is
new_list = source_list[:-1]
The source list is not modified. A new list is created with the contents of source list except for the last element.
Following is an example program, where we initialize a list, and copy this list without the last element using slicing.
Python Program
source_list = [8, 4, 7, 3, 6, 1, 9]
new_list = source_list[:-1]
print(source_list)
print(new_list)
Output
[8, 4, 7, 3, 6, 1, 9]
[8, 4, 7, 3, 6, 1]
The new list contains the elements of source list except for the last element.
2. List without last element using list.pop()
The syntax to get the list without last element using list.pop() method is
source_list.pop()
pop() method on list object without any argument removes the last element of the list. If you would like to keep the source list unchanged, you may first copy the source list to another new list and then pop from the new list.
Following is an example program, where we initialize a list, and use list.pop() method to get the list without last element.
Python Program
source_list = [8, 4, 7, 3, 6, 1, 9]
source_list.pop()
print(source_list)
Output
[8, 4, 7, 3, 6, 1]
As already mentioned, if you would like to keep a source list unchanged, you can make a copy of the source list and then do the popping.
In the following example, we will make a copy of the list, and then remove the last element from list.
Python Program
source_list = [8, 4, 7, 3, 6, 1, 9]
new_list = source_list.copy()
new_list.pop()
print(source_list)
print(new_list)
Output
[8, 4, 7, 3, 6, 1, 9]
[8, 4, 7, 3, 6, 1]
Summary
In this tutorial of Python Examples, we learned how to get the list without its last element, with the help of slicing and pop() method.