0
0
Pythonprogramming~5 mins

Tuple immutability in Python

Choose your learning style9 modes available
Introduction

Tuples are like boxes that keep things safe and unchanged. Once you put something inside, you cannot change it. This helps keep your data safe and reliable.

When you want to store a list of items that should not change, like days of the week.
When you want to use a fixed set of values as keys in a dictionary.
When you want to make sure data stays the same throughout your program.
When you want to return multiple values from a function without allowing changes.
Syntax
Python
my_tuple = (item1, item2, item3)
Tuples use parentheses ( ) to hold items separated by commas.
Once created, you cannot add, remove, or change items inside a tuple.
Examples
This creates a tuple named colors with three color names.
Python
colors = ('red', 'green', 'blue')
This creates an empty tuple with no items.
Python
empty_tuple = ()
For a single item tuple, include a comma after the item to make it a tuple.
Python
single_item = ('hello',)
Sample Program

This program shows that you cannot change items in a tuple. It tries to change the first item and catches the error. Then it prints the first item to show reading works fine.

Python
my_tuple = (1, 2, 3)
print("Original tuple:", my_tuple)

# Trying to change the first item will cause an error
try:
    my_tuple[0] = 10
except TypeError as e:
    print("Error:", e)

# You can read items but not change them
print("First item:", my_tuple[0])
OutputSuccess
Important Notes

Tuples are faster than lists because they cannot change.

If you need to change data, use a list instead.

Even though tuples are immutable, if they contain mutable items like lists, those items can change.

Summary

Tuples hold items that cannot be changed after creation.

Trying to change a tuple item causes an error.

Use tuples when you want fixed, safe data.