remove last element from a tuple in python

Remove Last Element From Tuple in Python

In this tutorial, we will look at how to remove the last element from a tuple in Python with the help of some examples.

Tuples are immutable. That is, they cannot be altered after creating them. You can, however, create a copy of the tuple with the last element removed in Python.

remove last element from a tuple in python

You can use a slice operation to slice only the part of the tuple you want. Let’s look at how to do this with the help of some examples.

Slice the tuple from the start to the last element (but not including the last element) and then assign the resulting tuple to the original tuple variable.

# create a tuple
t = (1, 2, 3, 4, 5)
# remove last element
last_element_index = len(t)-1
t = t[:last_element_index]
print(t)

Output:

(1, 2, 3, 4)

The tuple now has the last element removed.

You can also use negative indexing, for example, -1 to represent the index of the last element. For example –

# create a tuple
t = (1, 2, 3, 4, 5)
# remove last element
t = t[:-1]
print(t)

Output:

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

(1, 2, 3, 4)

You can see that the resulting tuple does not have the last element from the original tuple.

Please note that we are not modifying the original tuple. Instead, we are creating a new tuple with the last element removed and then assigning it back to the variable storing the original tuple.

If you want to store an ordered collection of objects and are expecting to make some changes to this collection (for example, adding, removing, replacing elements, etc.), you should prefer using lists that are much more flexible than tuples.

For example, you can use the list pop() function to remove an element from a list using its index.

# create a list
ls = [1, 2, 3, 4, 5]
# remove last element
ls.pop(-1)
print(ls)

Output:

[1, 2, 3, 4]

Here, we used the list pop() function to remove the last element from a list. For more, refer to our detailed tutorial on removing the last element from a list in Python.

You might also be interested in –


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