TL; DR: Exceptions are your friend and the best approach to the assignment as indicated.
The OP clarified in a comment that itβs not really important for their use case to know what an index is. As accepted in the answers, using x in somelist is the best answer if you don't care.
But I assume that, as the initial question, you care about what an index is. In this case, I note that all other solutions require scanning the list twice, which can lead to a significant decrease in performance.
In addition, as the venerable Raymond Hettinger wrote in the commentary
Even if we had list.find that returned -1, you still would need to check if I would == -1 and take some action.
Therefore, I will return to the assumption in the original question that exceptions should be avoided. I suggest that exceptions be your friend. They have nothing to fear, they are ineffective, and in fact you need to be familiar with them in order to write good code.
So, I think the best answer is to simply use the try-except method:
try: i = somelist.index(x) except ValueError: # deal with it
βDealing with thisβ means that you must do what you need: set me to the sentinel value, raise your own exception, follow another code branch, etc.
nealmcb Dec 17 '17 at 18:33 2017-12-17 18:33
source share