3zzy 3zzy - 11 months ago 85
Python Question

Inserting an item 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')



Answer Source

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')