user200783
user200783

Reputation: 14346

Create a slightly modified copy of a Python tuple?

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]) ?

Upvotes: 2

Views: 129

Answers (4)

Daniel
Daniel

Reputation: 42778

Use tuple slicing, to build the new tuple:

t2 = t[:2] + (t[2] + 1,) + t[3:]

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

If you have large tuples and just wanted to increment at certain indexes without manually indexing:

tuple(e + 1 if i == 2 else e for i, e in enumerate(t))

As Jon commented if you have multiple indexes you can use a set of indexes you want to increment:

 tuple(e + 1 if i in {1,3} else e for i, e in enumerate(t))

Upvotes: 3

Anzel
Anzel

Reputation: 20563

Alternatively you can use numpy and build a list of values you want to increment, then simply add them together, for example:

In [6]: import numpy as np

# your tuple
In [7]: t1 = (1, 2, 3, 4, 5)

# your list of values you want to increment
# this acts as a mask for mapping your values
In [8]: n = [0, 0, 1, 0, 0]

# add them together and numpy will only increment the respective position value
In [9]: np.array(t1) + n
Out[9]: array([1, 2, 4, 4, 5])

# convert back to tuple
In [10]: tuple(np.array(t1) + n)                                            
Out[11]: (1, 2, 4, 4, 5)

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 122096

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.

Upvotes: 5

Related Questions