Python program to remove last element from Tuple
Last Updated :
27 Jul, 2023
Given a tuple, the task is to write a Python program to delete the last element in the tuple in Python.
Example:
Input: (“geeks”, “for”, “geeks”)
Output:(“geeks”, “for”)
Explanation: Here we are deleting the last element of the tuple and finally modifying the original one.
Note: Tuples are immutable datatypes i.e. they cannot be modified therefore other than slicing we cannot modify a tuple but what we can do is that we can convert a tuple into list and then perform operations according to our need.
Remove the last element from Tuple Using positive indexing
Python3
tuple = ( "geeks" , "for" , "geeks" )
l_element = len ( tuple ) - 1
tuple = tuple [:l_element]
print ( tuple )
|
Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of tuple.
Explanation:
Here simply we find the index of the last element as (length of tuple-1) and then we update the current tuple with the modified or slicing tuple till the last element(excluding it).
Remove the last element from Tuple Using negative indexing
Python3
tuple = ( "geeks" , "for" , "geeks" )
tuple = tuple [: - 1 ]
print ( tuple )
|
Explanation:
Here instead of finding the index of the last element we directly write -1( that denotes the last element in the iterable) and then simply slicing it till the last element and update the existing tuple.
Remove last element from Tuple Using lists
Python3
tu = ( 1 , 2 , 3 , 4 , 5 )
tu = list (tu)
tu.pop( - 1 )
tu = tuple (tu)
print (tu)
|
Explanation:
As tuples are immutable we cannot directly modify them therefore first we convert it into lists then pop the last element.
Remove last element from Tuple Using lists remove() method
Python3
tu = ( 1 , 2 , 3 , 4 , 5 )
tu = list (tu)
tu.remove(tu[ - 1 ])
tu = tuple (tu)
print (tu)
|
Remove last element from Tuple Using the filter() function.
Algorithm:
- Define a tuple “tu” containing the values (1, 2, 3, 4, 5).
- Use the filter function with a lambda function to remove the last element of the tuple. The lambda function checks
- whether the current element is not equal to the last element of the tuple.
- Convert the resulting filter object back to a tuple and store it in the variable “tu”.
- Print the updated tuple “tu”.
Python3
tu = ( 1 , 2 , 3 , 4 , 5 )
tu = tuple ( filter ( lambda x: x ! = tu[ - 1 ], tu))
print (tu)
|
Time complexity:
The time complexity of this algorithm is O(n), where n is the length of the tuple “tu”. This is because the filter function and the tuple conversion both have a linear time complexity in the size of the input, and the lambda function is executed n times for a tuple of length n.
Auxiliary Space:
The space complexity of this algorithm is O(n), where n is the length of the tuple “tu”. This is because a new tuple is created to store the filtered elements, which requires memory proportional to the size of the input tuple.
Please Login to comment...