Inserting an item in a Tuple [duplicate]
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')
Since tuples are immutable, this will result in a new tuple. Just place it back where you got the old one.
sometuple + (someitem,)
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.
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