[Tutor] list.index method

Michael P. Reilly arcege@shore.net
Fri, 12 May 2000 11:43:37 -0400 (EDT)


> Yes, I did that as well (or something very much like it), but still, it has
> the possible drawback that it
> is a method implemented in python, instead of beeing builtin at the
> C-level. I don't really know if
> this means a much slower execution, but I suspect so. Anyway, this is just
> a matter of aestetics
> (how do we spell this in english?). I'm used to fortran arrays, where you
> have to search the array
> by iterating over the array index (fortran90/95 very much improved this,
> with array syntax), so I
> know how to solve my problem, but in an very ugly way... At least for
> python standards. Extending
> UserList  is much more beautifull, but I keep wondering why the list.index
> method was designed as
> it is. Optimization issues, perhaps?

It is not for optimization, it is simply so class instance, which are
to create abstractions of data, can be searched inside lists as be
equal but not unique.  As soon as you start testing, by default, by
uniqueness, then a large number of applications will be out of reach.

For example.. 
>>> class A:     # test with "is", by default
...   def __init__(self, v):
...     self.value = v
...
>>> class B(A):  # test by value (==)
...   def __cmp__(self, other):
...     return cmp(self.value, other)
...   def __rcmp__(self, other):          # don't worry about data cases
...     return cmp(B(other), self.value)  # this is overly simplified
...
>>> list1 = [ A(0.0), A(1.0), A(2.0), A(1.0) ]
>>> list1.index( 1.0 )
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: list.index(x): x not in list
>>> list1.index( list1[3] )
3
>>> list2 = [ B(0.0), B(1.0), B(2.0), B(1.0) ]
>>> list2.index( 1.0 )
1
>>> list2.index( list2[3] )
1
>>> list2.count( 1.0 )
2
>>> list2.count( 1.0 )
0
>>>

If list.index (and list.count) tested by uniqueness, then you could not
create abstract objects to interact with other objects "objA == objB",
and that is likely to be more valuable in the general application than
always testing by uniqueness.

The default for instances is to compare by uniqueness (is) - unless you
define __cmp__/__rcmp__ methods in the class hierarchy, then it is by
equivalence (==/!=/</>/<=/>=).

For these methods, it is up to the object, not the list.index method
(or list.count, or...) to determine what kind of test.  As Emile has
shown, it is easy enough to make an alternative method to do what you
want. :)

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------