Fix Python – list.index() function for Python that doesn’t throw exception when nothing found

Question

Asked By – Yarin

Python’s list.index(x) throws an exception if the item doesn’t exist. Is there a better way to do this that doesn’t require handling exceptions?

Now we will see solution for issue: list.index() function for Python that doesn’t throw exception when nothing found


Answer

If you don’t care where the matching element is, then use:

found = x in somelist

If you do care, then use a LBYL style with a conditional expression:

i = somelist.index(x) if x in somelist else None

This question is answered By – Raymond Hettinger

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0