The simple and best way is to use slice notation to remove the first and last element from the list in Python. Use the expression lst = lst[1:-1]
to iterate over a sequence starting from the start
index (included) and ending in the element at stop
index (excluded).
Remove the first and last element from the list of Python
Simple example code.
lst = ['Alice', 'Bob', 'Carl', 'Dave']
lst = lst[1:-1]
print(lst)
# empty list with zero elements
el = []
res = el[1:-1]
print(res)
Output:
You can also use the list.pop(0)
method. You can call both to remove the first and the last elements if the list has at least two elements.
lst = ['Alice', 'Bob', 'Carl', 'Dave'] lst.pop() # remove last lst.pop(0) # remove first print(lst) # ['Bob', 'Carl']
Keep in mind that this doesn’t modify the original list but creates a new one. If you want to modify the original list in place, you can use list slicing directly:
my_list = [1, 2, 3, 4, 5]
# Remove the first and last elements in place
my_list = my_list[1:-1]
print(my_list)
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.