Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 283
Yarin Avatar asked Nov 19 '11 21:11

Yarin


People also ask

What does index () return if not found Python?

The index() method searches for the first occurrence of the given item and returns its index. If specified item is not found, it raises 'ValueError' exception. The optional arguments start and end limit the search to a particular subsequence of the list.

Can you index an empty list?

Empty list has no index.

What will be returned if you look for the index of something that does not exist?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


2 Answers

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 
like image 185
Raymond Hettinger Avatar answered Sep 23 '22 20:09

Raymond Hettinger


TL;DR: Exceptions are your friend, and the best approach for the question as stated.
It's easier to ask for forgiveness than permission (EAFP)

The OP clarified in a comment that for their use case, it wasn't actually important to know what the index was. As the accepted answer notes, using x in somelist is the best answer if you don't care.

But I'll assume, as the original question suggests, that you do care what the index is. In that case, I'll note that all the other solutions require scanning the list twice, which can bring a large performance penalty.

Furthermore, as the venerable Raymond Hettinger wrote in a comment

Even if we had list.find that returned a -1 you would still need to test to see if the i == -1 and take some action.

So I'll push back on the assumption in the original question that exceptions should be avoided. I suggest that exceptions are your friend. They're nothing to be scared of, they aren't inefficient, and in fact you need to be conversant with them to write good code.

So I think the best answer is to simply use a try-except approach:

try:     i = somelist.index(x)  except ValueError:     # deal with it 

"deal with it" just means do what you need to do: set i to a sentinel value, raise an exception of your own, follow a different code branch, etc.

This is an example of why the Python principle Easier to ask for forgiveness than permission (EAFP) makes sense, in contrast to the if-then-else style of Look before you leap (LBYL)

like image 34
nealmcb Avatar answered Sep 23 '22 20:09

nealmcb