Why are tuples immutable?
steven.bethard at gmail.com
Fri Dec 17 10:19:46 CET 2004
> Why can't we __setitem__ for tuples?
It seems from your suggestions here that what you really want is a
single sequence type, list, instead of two sequence types: tuple and
list. Under your design, list would support hash, and it would be up to
the programmer to make sure not to modify a list when using it as a key
to a dict. The important thing to understand is that, while this is not
an unreasonable design decision, it's not the design decision that's
been made for Python.
Reading the docs and some of GvR's comments on python-dev, my
understanding is that, while a single sequence type would have sufficed,
the belief was that there were two mostly non-overlapping sets of tasks
that one might want to do with sequences. One set of tasks dealt with
"small collections of related data which may be of different types which
are operated on as a group" (tuples), while the other set of tasks
dealt with "hold[ing] a varying number of objects all of which have the
same type and which are operated on one-by-one" (lists).
Now, when you use a sequence as a key to a dict, you're operating on the
sequence as a group, not one-by-one. Given the above conceptions of
tuple and list then, it is natural to provide tuple with hash support,
while leaving it out of list.
Note also that tuples being immutable also falls out of the tuple
description above too. If you're operating on the sequence as a group,
then there's no need for __setitem__; __setitem__ is used to operate on
a sequence one-by-one.
I understand that you'd like a type that is operated on one-by-one, but
can also be considered as a group (e.g. is hashable). Personally, I
don't have any use for such a type, but perhaps others do. The right
solution in this case is not to try to redefine tuple or list, but to
write a PEP and suggest a new datatype that serves your purposes.
I'll help you out and provide you with an implementation: =)
Now all you need to do is write the Abstract, Motivation and Rationale,
and persuade the people on c.l.py and python-dev that this is actually a
useful addition to the language.
More information about the Python-list