tuples, index method, Python's design
carsten at uniqsys.com
Mon Apr 9 15:08:26 CEST 2007
On Mon, 2007-04-09 at 11:50 +1000, Steven D'Aprano wrote:
> On Sun, 08 Apr 2007 20:10:21 -0400, Carsten Haese wrote:
> > Will tuples also get a sort method? What about append and extend? pop?
> > __iadd__? __delslice__?
> Since tuples are immutable, no.
> If you see tuples as an immutable list, having an index method is quite
> useful. If you see them as structs, an index method is useless.
Let's recall what GvR said:
For tuples, I suspect such a function would rarely be used; I think
that is most cases where x.index() would be useful, x is generally a
list, whose contents varies in time, rather than a tuple (which cannot
In Guido's opinion, it's not the "structness" of tuples that negates the
need for tuple.index, it's their inability to be mutated easily. So
Guido seems to disagree with your notion that an index method is quite
useful for immutable lists.
I won't presume to speak for Guido, but if I had to connect the dots
between "tuples are immutable" and "tuples will rarely need an index
method", I'd do it like this: Consider an object X and a tuple T. Tuples
have "X in T" tests, so you can check if there exists some N such that
T[N]==X. The lack of the index method means you won't know the value of
N, but what would knowing N give you? You can't modify T, so all you can
do is read T[N], but you already know that that's going to return X, so
you might as well just use X.
Any use case for actually having to know N would have to involve an
operation where you end up explicitly using an index other than N, such
as slicing T from 0 to N-1, or looking at T[2*N] or something like that.
Of course such operations might be useful, but algorithms that need an
operation like that would self-document their design more clearly by
using a list instead of a tuple.
I hope this explains at least to some people how this seemingly
gratuitous inconsistency can actually be viewed as a justified design
More information about the Python-list