pythonpython-3.xlisttuples

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


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)

Solution

  • 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?