Skip to content
Related Articles

Related Articles

Python – Edit objects inside tuple

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 28 Jun, 2022

Sometimes, while working with tuples, being immutable, can offer a lot of confusion regarding its working. One of the questions that can pop from mind is, that 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 way in which edit inside objects of tuples can be performed. This occurs similar to any other container and inplace 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 above functionalities can also be used to solve this problem. In this, we perform task of removal using pop() and add element at 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)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!