2

I have a list of tuples:

tup = [('a', '10', 0xA), ('b', '9', 0x9)]

I am trying to change the values of the 3rd element in it

My attempt:

for i, elements in enumerate(tup):
    elements = list(elements)
    elements[2] = 0x99

When I check the contents of the tuple, it does not update with new my value.

Input: [i for i in tup] Output: [('a', '10', 10), ('b', '9', 9)]

Clearly a significant misunderstanding of how these data structures work on my part.

Any help appreciated.

Cheers

arsenal88
  • 1,040
  • 2
  • 15
  • 32

2 Answers2

2

Convert it to a list and update the values. And the you can change it back to tuple.

Ex:

tup = [('a', '10', 0xA), ('b', '9', 0x9)]
res = []
for i in tup:
    val = list(i)
    val[-1] = 0x99
    res.append(tuple(val))

print(res)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
-1

That is not possible:

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