list.index

Fredrik Lundh fredrik at pythonware.com
Fri Jun 6 10:01:19 EDT 2003


"delphiro" <delphiro at zonnet.nl> wrote:

> is this the easiest way to check for the existance of an item in a list?
> it looks a bit weird to check a for a listitem by using a try..except block
>
> (code background; if the item is found the colour should change
> else the colour that was already given is ok)
> [mycode]
> try:
>   x = self.selected_points.index( self.pointmarker )
>   colour = DEFAULT_SELECTED_POINT_COLOUR
> except ValueError:
>   pass
> [/mycode]

the usual way to do this is:

    if self.pointmarker in self.selected_points:
        colour = DEFAULT_SELECTED_POINT_COLOUR

you can also use "find", which does the same thing as "index" if
successful, but returns -1 if the item is not found.

    if self.selected_points.find(self.pointmarker) >= 0:
        colour = DEFAULT_SELECTED_POINT_COLOUR

</F>








More information about the Python-list mailing list