[python] 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')

Possible?

Thanks!

This question is related to python insert tuples

The answer is


You can code simply like this as well:

T += (new_element,)

one way is to convert it to list

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

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


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.


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

sometuple + (someitem,)

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

t= t + (6,7)

output :

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


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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to insert

How to insert current datetime in postgresql insert query How to add element in Python to the end of list using list.insert? Python pandas insert list into a cell Field 'id' doesn't have a default value? Insert a row to pandas dataframe Insert at first position of a list in Python How can INSERT INTO a table 300 times within a loop in SQL? How to refresh or show immediately in datagridview after inserting? Insert node at a certain position in a linked list C++ select from one table, insert into another table oracle sql query

Examples related to tuples

Append a tuple to a list - what's the difference between two ways? How can I access each element of a pair in a pair list? pop/remove items out of a python tuple Python convert tuple to string django: TypeError: 'tuple' object is not callable Why is there no tuple comprehension in Python? Python add item to the tuple Converting string to tuple without splitting characters Convert tuple to list and back How to form tuple column from two columns in Pandas