Home > Software engineering >  Item assignment to tuples
Item assignment to tuples

Time:03-20

I am trying to change the value of a particular element of a tuple of tuples. Here is the code:

y=((2,2),(3,3))
y[1][1]=999
print('y: ',y)

TypeError: 'tuple' object does not support item assignment

I understand that Tuples are immutable objects. “Immutable” means you cannot change the values inside a tuple. You can only remove them. I was wondering if there is a workaround? I cannot create a list of lists for y because I am using y as a key in a dictionary later.

CodePudding user response:

If you don't expect the modified value of y to point to the same dictionary entry, you could convert to a list of lists, modify that and then convert back to tuples. For example:

d = { ((2,2),(3,3)) : 'old', ((2, 2), (3, 999)) : 'new' }
y = ((2,2),(3,3))
print(d[y])
z = list(list(a) for a in y)
z[1][1] = 999
y = tuple(tuple(a) for a in z)
print(d[y])

Output:

old
new

CodePudding user response:

The workaround would be to convert it to the list, make changes, and then convert to the tuple again, if you need to use the tuple later as a key to a dictionary. There is no way to directly change the values.

y=((2,2),(3,3))
y = list(y)
for i in range(len(y)):
    y[i] = list(y[i])

y[1][1] = 999

for i in range(len(y)):
    y[i] = tuple(y[i])
y = tuple(y)

print('y: ',y)

CodePudding user response:

You can't change the values of tuples because they are constant. But, you can convert it back to a list to be changed.

Code:

x=((2,2),(3,3))
y = list(x)
print(y)
for i in range(len(y)):
    y[i] = list(x[i])
y[1][1]=999
print(y)
  • Related