Remove First and Last elements from Python List

This tutorial will discuss multiple ways to remove first and last elements from Python list.

Table Of Contents

Suppose we have a list of integers,

sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51]

We want to remove both the first and last elements from this list. There are multiple ways to achieve this:

Method 1: Using Slicing

Slicing allows us to select specific elements from a list.

To omit the first and last elements, we can slice from index 1 (the second element) to the second last element using negative indexing with -1. In Python, lists support negative indexing. Therefore, to exclude the first and last elements, we can slice the list from index position 1 to -1, as shown below:

sampleList = sampleList[1:-1]

This method will provide a new list excluding the first and last elements.

Let’s see the complete example,

# A List of Numbers
sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51]
print("Original List:", sampleList)

# Remove the first and last elements from List using slicing
sampleList = sampleList[1:-1]

print("List after removing first and last elements:")
print(sampleList)

Output

Original List: [45, 67, 22, 45, 22, 89, 71, 22, 51]
List after removing first and last elements:
[67, 22, 45, 22, 89, 71, 22]

Method 2: Using List.pop()

We can also use the pop() function of the list class to remove the first and last elements. To remove the last element, we call the pop method without any arguments and to remove the first element, we call the pop() function with the argument 0.

Let’s see the complete example,

# A List of Numbers
sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51]
print("Original List:", sampleList)

# Remove the last element
sampleList.pop()
# Remove the first element (index 0)
sampleList.pop(0)

print("List after removing first and last elements:")
print(sampleList)

Output

Original List: [45, 67, 22, 45, 22, 89, 71, 22, 51]
List after removing first and last elements:
[67, 22, 45, 22, 89, 71, 22]

Summary

Today, we learned about remove first and last elements from Python list.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top