Register Login

TypeError: 'tuple' object does not support item assignment

Updated May 03, 2020

TypeError: 'tuple' object does not support item assignment

In this article, we will learn about the error TypeError: "tuple" object does not support item assignment.
A tuple is a collection of ordered and unchangeable items as they are immutable. So once if a tuple is created we can neither change nor add new values to it.

The error TypeError: ‘tuple’ object does not support item assignment generates when we try to assign a new value in the tuple.

Let us understand it more with the help of an example.

Example:

# Creating a tuple 'MyTuple'
MyTuple = ("India", "USA", "UK")

# Changing 'UK' to 'Russia' at index 2
MyTuple[2] = "Russia"

# Print the tuple "MyTuple"
print(MyTuple)

Output:

File "tuple.py", line 4, in <module>
MyTuple[2] = "Russia" #This will raise an error
TypeError: 'tuple' object does not support item assignment

In the above example in line 4 of the code, we are trying to assign a new value at index 2. Thus raising the error TypeError: 'tuple' object does not support item assignment.

Solution:

To assign a new value in a tuple we can convert the tuple into a list, then after assigning convert the list back to the tuple as shown in the example below. Though it is recommended not to do so.

Example:

# Creating a tuple 'MyTuple'
MyTuple = ("India", "USA", "UK")

# Converting tuple to list
MyList = list(MyTuple)

# Changing 'UK' to 'Russia' at index 2
MyList[2] = "Russia"

# Converting list back to tuple
MyTuple = tuple(MyList)

# Printing the tuple
print(MyTuple)

Output:

('India', 'USA', 'Russia')

TypeError: 'tuple' object does not support item assignment


×