Python – Remove First And Last Element From List

In this tutorial, we will look at how to remove the first and last element from a Python list with the help of examples.

You can slice the list from the first element to the second last element to remove the first and last element from a Python list. The following is the syntax:

# remove first and last element from list
ls = ls[1:-1]

The slice operation returns a copy of the list with the first and the last element from the original list removed.

Let’s look at some examples –

Using the syntax from above, let’s remove the first and last element of a list containing two or more elements.

# create a list
ls = [1, 2, 3, 4, 5]
# remove first and last element from list
ls = ls[1:-1]
print(ls)

Output:

[2, 3, 4]

The resulting list does not contain the first and the last element from the original list. Note that here we used a negative index (-1) to represent the index of the last element in the list.

Let’s see what happens if we use the above syntax on a list with just one element.

# list with one element
ls = [1]
# remove first and last element from list
ls = ls[1:-1]
print(ls)

Output:

[]

The resulting list is an empty list. This is because the first and the last value in the list correspond to the same value, which, after removing gives an empty list.

Using the list slice method on an empty list does not return any error. (As against, using the list pop() function on an empty list to remove elements).

# empty list
ls = []
# remove first and last element from list
ls = ls[1:-1]
print(ls)

Output:

[]

It returns an empty list.

Note that you can also use the list function, pop() to remove elements from a list. You can refer to the following tutorials for more on how to use it.


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Leave a Reply

Your email address will not be published.