More pythonic way to change an element of a tuple?

Jeff Epler jepler at unpythonic.net
Wed Nov 27 14:25:02 EST 2002


On Wed, Nov 27, 2002 at 12:22:19PM -0600, Jeff Epler wrote:
> Of course, if you "mutate" your "tuples" less frequently than you access
> the dict with them, this will likely be slower, since you have the
> tuple() call once per get/set, instead of once per "mutate".
> 
> You could also hide this in a class.
>     class MutableTuple:
>         def __init__(self, t): self.t = t
> 
>         # Set up minimum code to act as a dict key
>         def __hash__(self): return hash(self.t)
>         def __cmp__(self, other): return cmp(self.t, other)
> 
>         # And the method to mutate
>         def inc(self, i):
>             self.t = increment_tuple_item(self.t, i)

.. and if you sometimes mutate more often than you access, and sometimes
access more often than you mutate, take a lazy approach.

    class MutableTuple:
        def ensure_list(self):
                if not isinstance(self.t, list): self.t = list(self.t)

        def ensure_tuple(self):
                if not isinstance(self.t, tuple): self.t = tuple(self.t)

        def __hash__(self):
                self.ensure_tuple()
                return hash(self.t)
        ...
        def inc(self, i):
                self.ensure_list()
                self.t[i] += 1

You might choose to inline ensure_list/ensure_tuple to avoid paying the
extra method-call overhead, however.

Jeff




More information about the Python-list mailing list