tuples, index method, Python's design

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Thu Apr 12 23:46:38 CEST 2007


On Thu, 12 Apr 2007 07:37:38 +0000, Antoon Pardon wrote:

> I once had a problem I like to solve by having a dictionary
> where the keys were multidimensional points on an integer grid.
> For a number of reasons I thought it would be easier if I could
> use lists, but most people argued that would be a bad idea and
> that I should use tuples, because they are immutable.

Also because code that raises "TypeError: list objects are unhashable" is
probably not going to work very well.


> Of course if I now would want to find out if the point is on an axis and
> which axis that is, I cannot use index because that is not available.

If memory is more important to you than speed:

class IndexTuple(tuple):
    def index(self, target):
        for i, x in enumerate(self):
            if x == target: return i
        raise ValueError

Or if speed is more important to you than memory:

class IndexTuple2(tuple):
    def index(self, target):
        return list(self).index(target)

If you prefer not to subclass, you can write an index function:

def index(sequence_or_mapping, target):
    try:
        return sequence_or_mapping.index(target)
    except AttributeError:
        return list(sequence_or_mapping).index(target)


So much fuss over such a little thing... yes it would be nice if tuples
grew an index method, but it isn't hard to work around the lack.



-- 
Steven.




More information about the Python-list mailing list