remove first and last element from a python list

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.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

# 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.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top