Why am I getting an error when I am trying to change a tuple

Question:

I am trying to change a tuple but, it keeps giving me this error:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    my_tuple[1] = 'y'
TypeError: 'tuple' object does not support item assignment

My code is:

my_tuple = (1,2,3,4,5)
my_tuple[1] = 'y'
print(my_tuple)
Asked By: snowhow

||

Answers:

Tuples are not lists

In a list, you can write a new value to any element of the list.

In a tuple, you can’t.

This property of tuples, "immutability", enables them to be used in different ways from lists, sometimes more efficiently.

Perhaps you would be better off with a list?

Answered By: Eureka

Tuples are immutable, if you want to change you can convert to list then back to tuple:

my_tuple = (1,2,3,4,5)
l=list(my_tuple)
l[1]='y'
my_tuple=tuple(l)

#(1, 'y', 3, 4, 5)

Tuples are immutable ordered and indexed collections of objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses.

https://python-reference.readthedocs.io/en/latest/docs/tuple/

Answered By: God Is One

the tuples, while are faster than lists, cannot be modified.
It would be more convenient to transform it back to list, modify and set it back to tuple.

my_list=list(my_tuple)
my_list[1]='y'
my_tuple=tuple(my_list)
Answered By: ilshatt

You cannot change an existing tuple. The only solution is to create a new tuple instance.

If that is acceptable you can do something like:

my_tuple = (1,2,3,4,5)
my_tuple = tuple('y' if i == 1 else x for i,x in enumerate(my_tuple))
print(my_tuple)
Answered By: user000001

its because tuples are constant, you can use list instead of tuples
like this

my_tuple = [1,2,3,4,5]
my_tuple[1] = 'y'
print(my_tuple)

you can check this link for more information
https://www.w3schools.com/python/python_tuples.asp

Answered By: 1aryo1

You can not change items in tuples in python, tuples are immutable.
If you want to change an item after you have made the variable you can better use a list like this:

my_list = [1,2,3,4,5]
my_list[1] = 'y'
print(my_list)
Answered By: Wijze
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.