Best way to handle list.index(might-not-exist) in python? Best way to handle list.index(might-not-exist) in python? python python

Best way to handle list.index(might-not-exist) in python?


There is nothing "dirty" about using try-except clause. This is the pythonic way. ValueError will be raised by the .index method only, because it's the only code you have there!

To answer the comment:
In Python, easier to ask forgiveness than to get permission philosophy is well established, and no index will not raise this type of error for any other issues. Not that I can think of any.


thing_index = thing_list.index(elem) if elem in thing_list else -1

One line. Simple. No exceptions.


The dict type has a get function, where if the key doesn't exist in the dictionary, the 2nd argument to get is the value that it should return. Similarly there is setdefault, which returns the value in the dict if the key exists, otherwise it sets the value according to your default parameter and then returns your default parameter.

You could extend the list type to have a getindexdefault method.

class SuperDuperList(list):    def getindexdefault(self, elem, default):        try:            thing_index = self.index(elem)            return thing_index        except ValueError:            return default

Which could then be used like:

mylist = SuperDuperList([0,1,2])index = mylist.getindexdefault( 'asdf', -1 )


matomo