Yes, I understand tuples are immutable but the situation is such that I need to insert an extra value into each tuple. So one of the items is the amount, I need to add a new item next to it in a different currency, like so:
('Product', '500.00', '1200.00')
Possible?
Thanks!
You can code simply like this as well:
T += (new_element,)
one way is to convert it to list
>>> b=list(mytuple)
>>> b.append("something")
>>> a=tuple(b)
def tuple_insert(tup,pos,ele):
tup = tup[:pos]+(ele,)+tup[pos:]
return tup
tuple_insert(tup,pos,9999)
tup: tuple
pos: Position to insert
ele: Element to insert
You absolutely need to make a new tuple -- then you can rebind the name (or whatever reference[s]) from the old tuple to the new one. The +=
operator can help (if there was only one reference to the old tuple), e.g.:
thetup += ('1200.00',)
does the appending and rebinding in one fell swoop.
Since tuples are immutable, this will result in a new tuple. Just place it back where you got the old one.
sometuple + (someitem,)
t = (1,2,3,4,5)
t= t + (6,7)
output :
(1,2,3,4,5,6,7)
For the case where you are not adding to the end of the tuple
>>> a=(1,2,3,5,6)
>>> a=a[:3]+(4,)+a[3:]
>>> a
(1, 2, 3, 4, 5, 6)
>>>
Source: Stackoverflow.com