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:
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.
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.
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
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
tup: tuple 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
answered Feb 22, 2010 at 7:10
John La RooyJohn La Rooy 285k51 gold badges358 silver badges498 bronze badges You can code simply like this as well:
answered Sep 8, 2016 at 4:19
VivekVivek 1821 gold badge3 silver badges7 bronze badges
output :
NelsonGon 12.7k5 gold badges26 silver badges54 bronze badges answered Jan 3, 2017 at 10:25
one way is to convert it to list
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.
|