Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an item in a Tuple [duplicate]

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!

like image 750
eozzy Avatar asked Feb 22 '10 07:02

eozzy


People also ask

Can we add duplicate values in tuple?

You can directly enter duplicate items in a Python tuple as it doesn't behave like a set(which takes only unique items).

How do you repeat a element in a tuple?

When it is required to repeat a tuple 'N' times, the '*' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error.

Does Python tuple allow duplicate elements?

Tuple — A tuple is an immutable ordered collection that allows duplicate elements.

How do you duplicate a tuple in Python?

copy. copy() and copy. deepcopy() just copy the reference for an immutable object like a tuple.


1 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') 
like image 155
swanson Avatar answered Sep 20 '22 07:09

swanson