how to mutate a tuple?

John Roth newsgroups at jhrothjr.com
Tue Oct 14 10:14:25 EDT 2003


"Carlo v. Dango" <oest at soetu.eu> wrote in message
news:oprw1cm4ytmyya52 at news.kadnet.dom...
> On Tue, 14 Oct 2003 09:33:46 -0400, Roy Smith <roy at panix.com> wrote:
>
> Many thanks for your quick reply!
>
> aaaahh so there is a tuper() construct! :) that helps a lot.. still this
> seems rather inefficient to create a list and then a new tuple.. but I
> guess there really is no easier way.
>
> but is there a tuple=>list function ? so that instead of creating the list
> by a for-construct I could just say
>
> list = tuple.tolist()
> list[0] = newval
> return turple(list)

No. If you think about it, for such a method to work, it would have
to change the object in place from a tuple to a list, otherwise none
of the bindings would work. If it did it in place, then a tuple
wouldn't be immutable, would it?

If you need to mutate a tuple, then I'd begin to question
whether there isn't something else wrong with the design.

John Roth
>
> ?
>
> -c.v.d.
>
>
> > Copy your input tuple to a list, then say "myTuple = tuple (myList)"
> >
> > myList = []
> > for item in myInputTuple:
> >    if this is the item that needs changing:
> >       item = something else
> >    myList.append (item)
> >
> > return tuple (myList)
>
>
>
> --






More information about the Python-list mailing list