Determinig position of a element in a list

Pedro Werneck pedro.werneck at bol.com.br
Mon Aug 25 16:20:53 EDT 2003


On Tue, 26 Aug 2003 00:29:04 +0200
"Przemo Drochomirecki" <pedrosch at gazeta.pl> wrote:

> i can implement function index (e.x. index(5,A) = -1, index(7,A) = 2),
> but maybe there's is simpler(builtin?) solution

I have a strange feeling that I misunderstood your question,
because the list.index() builtin is pretty obvious:

list.index(value, [start, [stop]])


If this is what you want, maybe you can use something like this:



def index(value, lst):
    try:
        i = list.index(lst, value)
        return i
    except ValueError:
        return -1

a = [1,3,7,11,14,15]

assert index(3, a) == 1
assert index(12, a) == -1

or maybe:

class Ilist(list):
    def index(self, *args):
        try:
            i = list.index(self, *args)
            return i
        except ValueError:
            return -1


a = Ilist([1,3,7,11,14,15])

assert a.index(3) == 1
assert a.index(12) == -1


Rgds

Pedro








More information about the Python-list mailing list