list index()

Ben Finney bignose+hates-spam at benfinney.id.au
Thu Aug 30 03:09:36 EDT 2007


zzbbaadd at aol.com writes:

> What's with the index() function of lists throwing an exception on not
> found?

It's letting you know that the item isn't in the list. There's no
sensible return value from an "index" function in that condition.

> Let's hope this is rectified in Python 3. If nothing else, add a
> function that doesn't throw an exception.

You can easily create one:

    def get_an_index_even_if_not_found(the_list, the_item):
        bogus_index_value = object()
        try:
            index = the_list.index(the_value)
        except ValueError:
            index = bogus_index_value
        return index

It's up to you to figure out what bogus_index_value you want to
use. The rest of us will continue to catch the exception where needed.

-- 
 \      "Reichel's Law: A body on vacation tends to remain on vacation |
  `\         unless acted upon by an outside force."  -- Carol Reichel |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list