how to mutate a tuple?

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Oct 14 09:37:40 EDT 2003


"Carlo v. Dango" <oest at soetu.eu> wrote in
news:oprw1bf9j4myya52 at news.kadnet.dom: 

> Hello there. I have a function which as an argument takes a tuple and 
> either returns that tuple or a mutated version of it. The problem is
> that tuples are imutable, hence I have to create a new tuple and copy
> the content of the old tuple to a new one.
> 
> But how do I do this if I only at runtime know the size of the tuple?
> I wish I could pass around lists instead.. that would be so much
> easier, but I'm passing "*args" and "**kwargs" around so I'm not
> really the one deciding the use of tuples or lists ;)
> 

On entry to your function, convert the original tuple to a list, then 
mutate the list and convert it back to a tuple when returning.

e.g.

>>> def ChangeIt(aTuple):
   work = list(aTuple)
   work[0] = "Hello"
   return tuple(work)

>>> ChangeIt((1,2,3))
('Hello', 2, 3)
>>> 


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list