I have a tuple (x,y) where x is a string and y is an integer.
Now I want to perform an operation on y, like y += 1, without wanting to create a new tuple. How can I do that?
Tuples are immutable, so you can't directly modify the variable
>>> t = ('foobar', 7)
>>> t[1] += 1
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
t[1] += 1
TypeError: 'tuple' object does not support item assignment
So you'd have to assign back a new tuple
>>> t = (t[0], t[1]+1)
>>> t
('foobar', 8)
You can't - tuples are immutable. Any attempt of changing an existing tuple would result in TypeError: 'tuple' object does not support item assignment.
What can be done is re-binding object name to a new tuple based on the previous one.
t = ('a', 1)
t = (t[0], t[1]+1)
assert t == ('a', 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With