"Find" in list of objects

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Oct 23 04:36:43 EDT 2008


En Thu, 23 Oct 2008 05:23:51 -0200, Andreas Müller <hufflehuffle at west.de>  
escribió:

> (Python 2.2.3 if this is relevant :-)
>
> I have a list of objects with, lets say, the attributes "ID", "x" and
> "y". Now I want to find the index of list element with ID=10.
>
> Of course I can loop through the list manually, but is there a
> construct like
>
> list.find (10, key='ID')

If you define __eq__ for your objects you may use list.index:

class Obj:
   def __init__(self, id_, x=0, y=0):
     self.id = id_
     self.x = x
     self.y = y
   def __eq__(self, other):
     if not isinstance(other, Obj): raise NotImplementedError
     return self.id==other.id

py> a = Obj(10)
py> b = Obj(11)
py> c = Obj(12)
py> alist = [a,b,c]
py> print alist.index(Obj(11))
1
py> print alist.index(Obj(20))
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list

Note that this is a "global" change - two separate instances with the same  
ID were "not equal" before, and are "equal" now, everywhere, not just  
regarding list.index

Of course you always have the old "for" loop solution (`enumerate` would  
make things a lot nicer, but it requires 2.3):

def index_by_id(alist, id_):
   for i in range(len(alist)):
     if alist[i].id==id_:
       return i

-- 
Gabriel Genellina




More information about the Python-list mailing list