Tuple object does not support item assignment

Tuple Object Does Not Support Item Assignment. Why?

Have you ever seen the error “tuple object does not support item assignment” when working with tuples in Python? In this article we will learn why this error occurs and how to solve it.

The error “tuple object does not support item assignment” is raised in Python when you try to modify an element of a tuple. This error occurs because tuples are immutable data types. It’s possible to avoid this error by converting tuples to lists or by using the tuple slicing operator.

Let’s go through few examples that will show you in which circumstances this error occurs and what to do about it.

Let’s get started!

Explanation of the Error “Tuple Object Does Not Support Item Assignment”

Define a tuple called cities as shown below:

cities = ('London', 'Paris', 'New York') 

If you had a list you would be able to update any elements in the list.

But, here is what happens if we try to update one element of a tuple:

>>> cities[1] = 'Rome'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment 

Tuples are immutable and that’s why we see this error.

But…

There is a workaround to this, we can:

  1. Convert the tuple into a list.
  2. Update any elements in the list.
  3. Convert the final list back to a tuple.

To convert the tuple into a list we will use the list() function:

>>> cities_list = list(cities)
>>> type(cities_list)
<class 'list'> 

Now, let’s update the element at index 1 in the same way we have tried to do before with the tuple:

>>> cities_list[1] = 'Rome'
>>> cities_list
['London', 'Rome', 'New York'] 

You can see that the second element of the list has been updated.

Finally, let’s convert the list back to a tuple using the tuple() function:

>>> tuple(cities_list)
('London', 'Rome', 'New York') 

Makes sense?

Avoid the “Tuple Object Does Not Support Item Assignment” Error with Slicing

The slicing operator also allows to avoid this error.

Let’s see how we can use slicing to create a tuple from our original tuple where only one element is updated.

We will use the following tuple and we will update the value of the element at index 2 to ‘Rome’.

cities = ('London', 'Paris', 'New York', 'Madrid', 'Lisbon') 

Here is the result we want:

('London', 'Paris', 'Rome', 'Madrid', 'Lisbon') 

We can use slicing and concatenate the first two elements of the original tuple, the new value and the last two elements of the original tuple.

Here is the generic syntax of the slicing operator (in this case applied to a tuple).

tuple_object[n:m]

This takes a slice of the tuple including the element at index n and excluding the element at index m.

Firstly, let’s see how to print the first two and last two elements of the tuple using slicing…

First two elements

>>> cities[0:2]
('London', 'Paris') 

We can also omit the first zero considering that the slice starts from the beginning of the tuple.

>>> cities[:2]
('London', 'Paris') 

Last two elements

>>> cities[3:]
('Madrid', 'Lisbon') 

Notice that we have omitted index m considering that the slice includes up to the last element of the tuple.

Now we can create the new tuple starting from the original one using the following code:

>>> cities[:2] + ('Rome',) + cities[3:]
('London', 'Paris', 'Rome', 'Madrid', 'Lisbon') 

(‘Rome’,) is a tuple with one element of type string.

Does “Tuple Object Does Not Support Item Assignment” Apply to a List inside a Tuple?

Let’s see what happens when one of the elements of a tuple is a list.

>>> values = (1, '2', [3]) 

If we try to update the second element of the tuple we get the expected error:

>>> values[1] = '3'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment 

If we try to assign a new list to the third element…

>>> values[2] = [3,4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment 

…once again we get back the error “‘tuple’ object does not support item assignment“.

But if we append another number to the list inside the tuple, here is what happens:

>>> values[2].append(4)
>>> values
(1, '2', [3, 4]) 

The Python interpreter doesn’t raise any exceptions because the list is a mutable data type.

This concept is important for you to know when you work with data types in Python:

In Python, lists are mutable and tuples are immutable.

How to Solve This Error with a List of Tuples

Do we see this error also with a list of tuples?

Let’s say we have a list of tuples that is used in a game to store name and score for each user:

users = [('John', 345), ('Mike', 23), ('Richard', 876)]

The user John has gained additional points and I want to update the points associated to his user:

>>> users[0][1] = 400
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment 

When I try to update his points we get back the same error we have seen before when updating a tuple.

How can we get around this error?

Tuples are immutable but lists are mutable and we could use this concept to assign the new score to a new tuple in the list, at the same position of the original tuple in the list.

So, instead of updating the tuple at index 0 we will assign a new tuple to it.

Let’s see if it works…

>>> users[0] = ('John', 400)
>>> users
[('John', 400), ('Mike', 23), ('Richard', 876)] 

It does work! Once again because a list is mutable.

And here is how we can make this code more generic?

>>> users[0] = (users[0][0], 400)
>>> users
[('John', 400), ('Mike', 23), ('Richard', 876)] 

Ok, this is a bit more generic because we didn’t have to provide the name of the user when updating his records.

This is just an example to show you how to address this TypeError, but in reality in this scenario I would prefer to use a dictionary instead.

It would allow us to access the details of each user from the name and to update the score without any issues.

Tuple Object Does Not Support Item Assignment Error With Values Returned by a Function

This error can also occur when a function returns multiple values and you try to directly modify the values returned by the function.

I create a function that returns two values: the number of users registered in our application and the number of users who have accessed our application in the last 30 days.

>>> def get_app_stats():
...     users_registered = 340
...     last_30_days_logins = 2003
...     return users_registered, last_30_days_logins
... 
>>> stats = get_app_stats()
>>> stats
(340, 2003) 

As you can see the two values are returned by the function as a tuple.

So, let’s assume there is a new registered user and because of that I try to update the value returned by the function directly.

I get the following error…

>>> stats[0] = stats[0] + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment 

This can happen especially if I know that two values are returned by the function but I’m not aware that they are returned in a tuple.

Why Using Tuples If We Get This Error?

You might be thinking…

What is the point of using tuples if we get this error every time we try to update them?

Wouldn’t be a lot easier to always use lists instead?

We can see the fact that tuples are immutable as an added value for tuples when we have some data in our application that should never be modified.

Let’s say, for example, that our application integrates with an external system and it needs some configuration properties to connect to that system.

ext_system_config = ('api.ext.system.com', '443')

The tuple above contains two values: the API endpoint of the system we connect to and the port for their API.

We want to make sure this configuration is not modified by mistake in our application because it would break the integration with the external system.

So, if our code inadvertently updates one of the values, the following happens:

>>> ext_system_config[0] = 'incorrect_value'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment 

Remember, it’s not always good to have data structures you can update in your code whenever you want.

Conclusion

In this article we have seen when the error “tuple object does not support item assignment” occurs and how to avoid it.

You have learned how differently the tuple and list data types behave in Python and how you can use that in your programs.

If you have any questions feel free to post them in the comment below 🙂

Share knowledge with your friends!

Leave a Reply

Your email address will not be published. Required fields are marked *