Write a python program to insert an element in a tuple

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 Feb 22, 2010 at 7:03

1

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 Feb 22, 2010 at 7:05

swansonswanson

7,1984 gold badges31 silver badges33 bronze badges

3

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

sometuple + (someitem,)

answered Feb 22, 2010 at 7:07

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 Feb 22, 2010 at 7:09

Alex MartelliAlex Martelli

823k163 gold badges1202 silver badges1379 bronze badges

6

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 Jul 22, 2015 at 18:18

Vidya SagarVidya Sagar

1,46614 silver badges23 bronze badges

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 Feb 22, 2010 at 7:10

Write a python program to insert an element in a tuple

John La RooyJohn La Rooy

285k51 gold badges358 silver badges498 bronze badges

You can code simply like this as well:

T += (new_element,)

answered Sep 8, 2016 at 4:19

VivekVivek

1821 gold badge3 silver badges7 bronze badges

t = (1,2,3,4,5)

t= t + (6,7)

output :

(1,2,3,4,5,6,7)

Write a python program to insert an element in a tuple

NelsonGon

12.7k5 gold badges26 silver badges54 bronze badges

answered Jan 3, 2017 at 10:25

one way is to convert it to list

>>> b=list(mytuple)
>>> b.append("something")
>>> a=tuple(b)

answered Feb 22, 2010 at 7:07

ghostdog74ghostdog74

313k55 gold badges252 silver badges339 bronze badges

Can we insert element in tuple?

In Python, since tuple is immutable, you cannot update it, i.e., you cannot add, change, or remove items (elements) in tuple . tuple represents data that you don't need to update, so you should use list rather than tuple if you need to update it.

How do you add elements to an empty tuple in Python?

You can't add a tuple and number. Your line should probably be newtup += (aTup[i],) . Haven't checked it though. Adding the parentheses and comma turns the number into a tuple with a single member.