Tuples and immutability

Ian Kelly ian.g.kelly at gmail.com
Sat Mar 1 00:34:56 EST 2014


On Fri, Feb 28, 2014 at 9:45 PM, Mark H. Harris <harrismh777 at gmail.com> wrote:
> I really believe IMHO that the error should have come when you made the list an item of a tuple.  An immutable object should have NO REASON to contain a mutable  object like list... I mean the whole point is to eliminate the overhead of a list ... why would the python interpreter allow you to place a mutable object within an immutable list in the first place.   This is just philosophical, and yes, the core dev's are not going to agree with me on this either.

One very common example of tuples containing lists is when lists are
passed to any function that accepts *args, because the extra arguments
are passed in a tuple.  A similarly common example is when returning
multiple objects from a function, and one of them happens to be a
list, because again they are returned in a tuple.

    def f(*args):
        print(args)
        return (args[1:])

    >>> result = f(1, 2, 3, [4, 5])
    (1, 2, 3, [4, 5])
    >>> print(result)
    (2, 3, [4, 5])

Both of these things are quite handy, and if you restrict tuples from
containing lists, then you lose both of them (or you switch to lists
and lose the optimization for no good reason).



More information about the Python-list mailing list