Determinig position of a element in a list

Asun Friere afriere at yahoo.co.uk
Mon Aug 25 22:43:15 EDT 2003


Erik Max Francis <max at alcyone.com> wrote in message news:<3F4A955B.B1659F4A at alcyone.com>...
> Przemo Drochomirecki wrote:
> 
> > i'm wondering if there is any tricky way for doing following thing:
> > ...
> > i can implement function index (e.x. index(5,A) = -1, index(7,A) = 2),
> > but
> > maybe there's is simpler(builtin?) solution
> 
> Yep, the -- wait for it -- .index method on the list object:

:)

But do note that, despite its name, 'list.index' does NOT return the
"position of an element in a list," but rather the position of the
_first equivalent_ element in a list.  Although for the example you
gave that amounts to the same thing.  Whether you regard this as a
wart or the only logical choice probably depends on the use to which
you want to put '.index'
  
eg.

>>> class MyInt(int) :
	pass

>>> a=MyInt(1);b=MyInt(2);c=MyInt(3);d=MyInt(2)
>>> l = [a,b,c,d]
>>> l[l.index(d)] == d
True
>>> l[l.index(d)] is d
False
>>>




More information about the Python-list mailing list