Why You Can't Change Tuple Elements in Python: Understanding Tuple Immutability
☰Fullscreen
Table of Content:
Tuples, as opposed to lists, are immutable objects.
This implies that after a tuple's elements have been specified, we cannot modify them. However, we can modify the nested elements of an element if the element itself is a mutable data type like a list.
A tuple can be assigned to many values (reassignment).
Example
# Python program to show that Python tuples are immutable objects # Creating a tuple tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4]) # Trying to change the element at index 2 try: tuple_[2] = "Items" print(tuple_) except Exception as e: print( e ) # But inside a tuple, we can change elements of a mutable object tuple_[-1][2] = 10 print(tuple_) # Changing the whole tuple tuple_ = ("Python", "Items") print(tuple_)
Output
'tuple' object does not support item assignment ('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4]) ('Python', 'Items')
To merge multiple tuples, we can use the + operator. Concatenation is the term for this.
Using the * operator, we may also repeat a tuple's elements for a specified number of times. This is already shown above.
The results of the operations + and * are new tuples.
Example
# Python program to show how to concatenate tuples # Creating a tuple tuple_ = ("Python", "Tuple", "Ordered", "Immutable") # Adding a tuple to the tuple_ print(tuple_ + (4, 5, 6))
Output
('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)