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 - 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
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 Access Tuple Item In Python, a tuple is a collection of ordered, immutable elements. Accessing the items in a tuple is easy and in this article, we'll explore how to access tuple elements in python using different methods.Access Tuple Items by IndexJust like lists, tuples are indexed in Python. The indexing starts fr
2 min read
Convert Tuple to Json Array in Python Python's versatility as a programming language extends to its rich data structures, including tuples and JSON. JSON, abbreviation for JavaScript Object Notation, is a lightweight data format used for representing structured data. Moreover, it is a syntax for storing and exchanging data. In this arti
3 min read
Python - Flatten Nested Tuples Sometimes, while working with Python Tuples, we can have a problem in which we need to perform flattening of tuples, which can be nested and undesired. This can have application across many domains such as Data Science and web development. Let's discuss certain way in which this task can be performe
7 min read
Unpacking Dictionary Keys into Tuple - Python The task is to unpack the keys of a dictionary into a tuple. This involves extracting the keys of the dictionary and storing them in a tuple, which is an immutable sequence.For example, given the dictionary d = {'Gfg': 1, 'is': 2, 'best': 3}, the goal is to convert it into a tuple containing the key
2 min read
Convert Dictionary to List of Tuples - Python Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
3 min read
Python - Clearing a tuple Sometimes, while working with Records data, we can have a problem in which we may require to perform clearing of data records. Tuples, being immutable cannot be modified and hence makes this job tough. Let's discuss certain ways in which this task can be performed. Method #1 : Using list() + clear()
4 min read