Immutability of Tuples and Exception Handling
In Python, once a tuple is created, its contents cannot be changed.
Attempting to violate the immutability of a tuple raises a TypeError
exception.
To prevent errors in your program due to unexpected attempts to violate tuple immutability, you can use a try
/except
statement.
A try
/except
statement executes the code in the except
block if an exception occurs in the try
block.
Handling Tuple Immutability Exceptions
my_tuple = (1, 2, 3) try: # Attempt to change the second element my_tuple[1] = 5 except TypeError as e: # Handle TypeError exception print(f"Error occurred: {e}")
In this code, trying to change the second element of the tuple with my_tuple[1] = 5
raises a TypeError
.
As shown in the example code, the except
block handles the TypeError
exception and prints the error message.
Mission
0 / 1
Attempting to change an element of a tuple results in a TypeError
.
O
X
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result