Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a slightly modified copy of a Python tuple?

Tags:

python

tuples

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]) ?
like image 359
user200783 Avatar asked Dec 19 '25 03:12

user200783


1 Answers

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.

like image 161
jonrsharpe Avatar answered Dec 20 '25 16:12

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!