I have a Python tuple, t, with 5 entries. t[2] is an int. How can I create another tuple with the same contents, but with t[2] incremented?
Is there a better way than:
t2 = (t[0], t[1], t[2] + 1, t[3], t[4]) ?
I would be inclined to use a namedtuple instead, and use the _replace method:
>>> from collections import namedtuple
>>> Test = namedtuple('Test', 'foo bar baz')
>>> t1 = Test(1, 2, 3)
>>> t1
Test(foo=1, bar=2, baz=3)
>>> t2 = t1._replace(bar=t1.bar+1)
>>> t2
Test(foo=1, bar=3, baz=3)
This also gives semantic meaning to the individual elements in the tuple, i.e. you refer to bar rather than just the 1th element.
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