0

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.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Garfield
  • 182
  • 7
  • Does this answer your question? [List vs tuple, when to use each?](https://stackoverflow.com/questions/1708510/list-vs-tuple-when-to-use-each) – Mateen Ulhaq Mar 19 '22 at 22:53
  • @MateenUlhaq I mean I understand the difference between lists and tuples. But I am wondering if there is a data structure that can be used for assignment and also be hashed in dictionaries. A tuple does not allow assignment but can be hashed. On the other hand, lists allow assignment but cannot be hashed. So is there a way to do both? – Garfield Mar 19 '22 at 22:55
  • 1
    Do you expect the modified value of `y` to refer to the same entry in the dictionary? – Nick Mar 19 '22 at 23:01
  • https://stackoverflow.com/questions/24217647/why-must-dictionary-keys-be-immutable – Nick Mar 19 '22 at 23:01
  • @Nick Thanks, no, the modified value of `y` would refer to a different key in the dictionary. – Garfield Mar 19 '22 at 23:04
  • 1
    Is there a reason you want to _modify_ y instead of just assigning it a new value? – John Gordon Mar 19 '22 at 23:15

3 Answers3

2

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
Nick
  • 138,499
  • 22
  • 57
  • 95
1

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)
mackostya
  • 141
  • 1
  • 6
0

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)
Blue Robin
  • 847
  • 2
  • 11
  • 31