views:

114

answers:

5

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!

+5  A: 

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')
swanson
Or any of a number of approaches that don't modify the original tuple, but replace it instead.
Steve314
+5  A: 

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

sometuple + (someitem,)
Ignacio Vazquez-Abrams
A: 

one way is to convert it to list

>>> b=list(mytuple)
>>> b.append("something")
>>> a=tuple(b)
ghostdog74
+4  A: 

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.

Alex Martelli
yes, as i learned the hard way :P += does not attempt to modify the reference in place, it reassigns
Matt Joiner
@Matt, exactly -- but with a tuple or string, that's all you can do (if you apply it to a list, it _does_ modify it in-place -- the "reassign" part is a negligible overhead),
Alex Martelli
Always gets my hackles up. += in my mind should be an in-place modification. If you can't do it, don't appear to be doing it. I'm not the Python spec though, and clearly whatever my opinion, it does what it's defined to do. And it's not an objectively sane complaint anyway - integers are mutable and you can += them easy enough, which again means replacement. Basically intuition-clash between language models.
Steve314
Oops - integers are *immutable* of course.
Steve314
@Steve314, if you can do `i+=j` where `i` is immutable by being an `int`, it's clearly irrational to rant against being able to do it when it's immutable by being another type on which `+` is defined.
Alex Martelli
In C++ you can + a const int, but not += a const int. I *said* I was being irrational (or rather "not objectively sane"), and I also said "intuition-clash between language models". And no-ones ranting - I was simply commenting. Though I may well have been ranting in the past when we had a related discussion on comp.lang.python.
Steve314
A: 

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