How to remove the last element from a tuple in Python
Hello programmers, in this tutorial, we will learn how to remove the last element from a tuple in Python.
As a tuple is an immutable object, thus we can not modify it. So we can do one thing to do our task. We have to first convert a tuple into a list then we can easily modify the list. Then we can convert the list into a tuple again.
After converting a tuple in the list then, we have many ways to remove the last element from a list.
pop() method to remove the last element from a tuple
This method removes the last element and returns the last element
Coding
- lets us have a tuple t, and we 1st convert it into the list using the list() method to remove the last element.
- At least we convert it back into tuple t using the tuple() method, and we print our tuple t.
#tuple t
t=(1,2,'a','b',2)
#converting tuple t into list l
l=list(t)
print("list: ",l)
#removing last element using pop() method
l.pop()
print("list after removing last element:", l)
#convert back into tuple
t=tuple(l)
#printing tuple after removing last element
print("tuple after removing last element:",t)output:
list: [1, 2, 'a', 'b', 2] list after removing last element: [1, 2, 'a', 'b'] tuple after removing last element: (1, 2, 'a', 'b')
Using the Index method
coding
- Instead of the pop method, we use a square bracket “[]” to take all the elements to the last 2nd.
- “l[:-1]” means all the elements from starting to the last 2nd element.
#tuple t
t=(1,2,'a','b',2)
#converting tuple t into list l
l=list(t)
print("list: ",l)
#removing last element using index method method
l=l[:-1]
print("list after removing last element:", l)
#convert back into tuple
t=tuple(l)
#printing tuple after removing last element
print("tuple after removing last element:",t)output:
list: [1, 2, 'a', 'b', 2] list after removing last element: [1, 2, 'a', 'b'] tuple after removing last element: (1, 2, 'a', 'b')
Leave a Reply