Python - Edit objects inside tuple
Last Updated :
01 Aug, 2023
Sometimes, while working with tuples, being immutable can offer a lot of confusion regarding its working. One of the questions that can pop into the mind is, Are objects inside tuples mutable? The answer to this is Yes. Let's discuss certain ways in which this can be achieved.
Method #1: Using Access methods
This is one of the ways in which edit inside objects of tuples can be performed. This occurs similarly to any other container and in place using list access method.
Python3
# Python3 code to demonstrate working of
# Edit objects inside tuple
# Using Access Methods
# initializing tuple
test_tuple = (1, [5, 6, 4], 9, 10)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Edit objects inside tuple
# Using Access Methods
test_tuple[1][2] = 14
# printing result
print("The modified tuple : " + str(test_tuple))
Output : The original tuple : (1, [5, 6, 4], 9, 10)
The modified tuple : (1, [5, 6, 14], 9, 10)
Method #2 : Using pop() + index()
The combination of the above functionalities can also be used to solve this problem. In this, we perform the task of removal using pop() and add an element at a particular index using index().
Python3
# Python3 code to demonstrate working of
# Edit objects inside tuple
# Using pop() + index()
# initializing tuple
test_tuple = (1, [5, 6, 4], 9, 10)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Edit objects inside tuple
# Using pop() + index()
test_tuple[1].pop(2)
test_tuple[1].insert(2, 14)
# printing result
print("The modified tuple : " + str(test_tuple))
Output : The original tuple : (1, [5, 6, 4], 9, 10)
The modified tuple : (1, [5, 6, 14], 9, 10)
Method #3 : Using the list
Approach
Convert the tuple to a list, edit the list, and convert it back to a tuple
Algorithm
1. Convert the tuple to a list using the list() function.
2. Edit the list by accessing the desired index and assigning a new value to it.
3. Convert the edited list back to a tuple using the tuple() function.
Python3
# Initial tuple
my_tuple = (1, 2, 3, 4, 5)
# Convert the tuple to a list
my_list = list(my_tuple)
# Edit the list
my_list[2] = 10
# Convert the list back to a tuple
my_tuple = tuple(my_list)
# Print the updated tuple
print(my_tuple)
Time Complexity: O(n), where n is the length of the tuple.
Space Complexity: O(n), where n is the length of the tuple.
Method #4: Using lambda function
Define a lambda function to modify the given tuple by replacing the element at the specified index with a new value.
Call the lambda function with the original tuple, index of the element to be replaced, and the new value.
Algorithm
1. Define a lambda function modify_tuple that takes three arguments - the original tuple, the index of the element to be replaced, and the new value.
2. Use slicing to create a new tuple that has the same elements as the original tuple up to the specified index, followed by the new value, and then the remaining elements of the original tuple.
3. Return the new tuple.
Python3
# Using lambda function to modify the tuple
modify_tuple = lambda tup, index, new_val: tup[:index] + (new_val,) + tup[index+1:]
# Example usage
tup = (1, [5, 6, 4], 9, 10)
new_tup = modify_tuple(tup, 1, [5, 6, 14])
print(new_tup)
Output(1, [5, 6, 14], 9, 10)
Time Complexity: O(1), since the lambda function performs a constant number of operations regardless of the size of the tuple.
Auxiliary Space: O(N), where N is the size of the original tuple. This is because a new tuple is created that contains the same number of elements as the original tuple.
Method #5: Using the slicing
Python3
# Initial tuple
my_tuple = (1, 2, 3, 4, 5)
# Convert the tuple to a list
my_list = list(my_tuple)
# Edit the list using slicing
my_list[2:3] = [10]
# Convert the list back to a tuple
my_tuple = tuple(my_list)
# Print the updated tuple
print(my_tuple)
Time complexity: The time complexity of this approach is O(n), where n is the length of the tuple.
Auxiliary space: The auxiliary space complexity is O(n), where n is the length of the tuple, as we are converting the tuple to a list.
METHOD 6:By creating a new tuple
APPROACH:
The approach modifies an object inside a tuple by creating a new tuple with the desired modification. It uses indexing and concatenation to replace the specified element in the tuple. The modified tuple is then printed as the output.
ALGORITHM:
1.Initialize the original tuple.
2.Create a new tuple by concatenating the desired modified parts with the original elements.
3.Output the modified tuple.
Python3
# Given input
tpl = (1, [5, 6, 4], 9, 10)
# Create a new tuple with the modified object
modified_tpl = tpl[:1] + ([tpl[1][0], tpl[1][1], 14] + tpl[1][3:],) + tpl[2:]
# Output
print("The modified tuple:", modified_tpl)
OutputThe modified tuple: (1, [5, 6, 14], 9, 10)
Time Complexity:
The time complexity of this approach is O(1) as it doesn't involve any iterative operations or looping. It simply performs indexing and concatenation, which take constant time regardless of the tuple size.
Space Complexity:
The space complexity of this approach is O(N), where N is the size of the modified list. In this case, since the modification involves replacing a single element, the space complexity is effectively O(1) as the list size remains constant.
Similar Reads
Python | Addition of tuples
Sometimes, while working with records, we might have a common problem of adding contents of one tuple with the corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Let's discuss certain ways in which this task can be performed. Metho
5 min read
Python - Iterate over Tuples in Dictionary
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print
2 min read
How to Append Objects in a List in Python
The simplest way to append an object in a list using append() method. This method adds an object to the end of the list. Pythona = [1, 2, 3] #Using append method to add object at the end a.append(4) print(a) Output[1, 2, 3, 4] Let's look into various other methods to append object in any list are:Ta
2 min read
Python | Sort lists in tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to sort the tuples which constitutes of lists and we need to sort each of them. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + sorted() + generator expression This task ca
5 min read
Python Tuple - len() Method
While working with tuples many times we need to find the length of the tuple, and, instead of counting the number of elements with loops, we can also use Python len(). We will learn about the len() method used for tuples in Python. Example: Python3 Tuple =( 1, 0, 4, 2, 5, 6, 7, 5) print(len(Tuple))
2 min read
Create Dictionary Of Tuples - Python
The task of creating a dictionary of tuples in Python involves mapping each key to a tuple of values, enabling structured data storage and quick lookups. For example, given a list of names like ["Bobby", "Ojaswi"] and their corresponding favorite foods as tuples [("chapathi", "roti"), ("Paraota", "I
3 min read
Convert List to Tuple in Python
The task of converting a list to a tuple in Python involves transforming a mutable data structure list into an immutable one tuple. Using tuple()The most straightforward and efficient method to convert a list into a tuple is by using the built-in tuple(). This method directly takes any iterable like
2 min read
Create Class Objects Using Loops in Python
We are given a task to create Class Objects using for loops in Python and return the result, In this article we will see how to create class Objects by using for loops in Python. Example: Input: person_attributes = [("Alice", 25), ("Bob", 30), ("Charlie", 35)]Output: Name: Alice, Age: 25, Name: Bob,
4 min read
Python | Add tuple to front of list
Sometimes, while working with Python list, we can have a problem in which we need to add a new tuple to existing list. Append at rear is usually easier than addition at front. Let's discuss certain ways in which this task can be performed. Method #1 : Using insert() This is one of the way in which t
7 min read
Print a List of Tuples in Python
The task of printing a list of tuples in Python involves displaying the elements of a list where each item is a tuple. A tuple is an ordered collection of elements enclosed in parentheses ( ), while a list is an ordered collection enclosed in square brackets [ ].Using print()print() function is the
2 min read