Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Edit objects inside tuple
When it is required to edit the objects inside a tuple, simple indexing can be used. While tuples are immutable, they can contain mutable objects like lists that can be modified in-place.
A tuple can store heterogeneous values (i.e data of any data type like integer, floating point, strings, lists, and so on). When a tuple contains mutable objects, those objects can be modified without changing the tuple's identity.
Example
Below is a demonstration of editing a list inside a tuple ?
my_tuple = (45, 67, [35, 66, 74], 89, 100)
print("The tuple is :")
print(my_tuple)
# Edit the list inside the tuple
my_tuple[2][1] = 63
print("The tuple after changes is :")
print(my_tuple)
The output of the above code is ?
The tuple is : (45, 67, [35, 66, 74], 89, 100) The tuple after changes is : (45, 67, [35, 63, 74], 89, 100)
Modifying Dictionary Inside Tuple
You can also modify dictionaries stored inside tuples ?
my_tuple = (10, {'name': 'John', 'age': 25}, 30)
print("Original tuple:")
print(my_tuple)
# Modify dictionary inside tuple
my_tuple[1]['age'] = 26
my_tuple[1]['city'] = 'New York'
print("Modified tuple:")
print(my_tuple)
The output of the above code is ?
Original tuple:
(10, {'name': 'John', 'age': 25}, 30)
Modified tuple:
(10, {'name': 'John', 'age': 26, 'city': 'New York'}, 30)
Key Points
- Tuples are immutable, meaning you cannot change their structure or replace elements
- However, if a tuple contains mutable objects (lists, dictionaries, sets), those objects can be modified
- The tuple's identity remains the same, only the contents of mutable objects change
- Use indexing to access and modify nested mutable objects:
my_tuple[index][nested_index]
Conclusion
While tuples are immutable, you can edit mutable objects stored within them using indexing. This allows modification of lists, dictionaries, or other mutable types without changing the tuple's structure.
