Inserting an item in a Tuple

Question:

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!

Asked By: eozzy

||

Answers:

You can cast it to a list, insert the item, then cast it back to a tuple.

a = ('Product', '500.00', '1200.00')
a = list(a)
a.insert(3, 'foobar')
a = tuple(a)
print a

>> ('Product', '500.00', '1200.00', 'foobar')
Answered By: swanson

Since tuples are immutable, this will result in a new tuple. Just place it back where you got the old one.

sometuple + (someitem,)

one way is to convert it to list

>>> b=list(mytuple)
>>> b.append("something")
>>> a=tuple(b)
Answered By: ghostdog74

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.

Answered By: Alex Martelli

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)
>>> 
Answered By: John La Rooy
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

Answered By: Vidya Sagar

You can code simply like this as well:

T += (new_element,)
Answered By: Vivek
t = (1,2,3,4,5)

t= t + (6,7)

output :

(1,2,3,4,5,6,7)
Answered By: hardik patel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.