List.index () for Python, which does not throw an exception when nothing is found

Python list.index(x) throws an exception if the item does not exist. Is there a better way to do this that does not require exception handling?

+45
python
Nov 19 2018-11-11T00:
source share
9 answers

If you don't care where the corresponding item is, use:

 found = x in somelist 

If you don't care, use the LBYL style with a conditional expression:

 i = somelist.index(x) if x in somelist else None 
+53
Nov 19 2018-11-21T00:
source share

implement your own index for a list?

 class mylist(list): def index_withoutexception(self,i): try: return self.index(i) except: return -1 

So, you can use the list, and with your index, return what you want in case of an error.

You can use it as follows:

  l = mylist([1,2,3,4,5]) # This is the only difference with a real list l.append(4) # l is a list. l.index_withoutexception(19) # return -1 or what you want 
+4
Nov 19 '11 at 21:16
source share

Write a function that does what you need:

 def find_in_iterable(x, iterable): for i, item in enumerate(iterable): if item == x: return i return None 

If you only need to know if an element exists, but not an index, you can use in :

 x in yourlist 
+3
Nov 19 2018-11-21T00:
source share

Yes there is. You can, for example. do something similar to this:

 test = lambda l, e: l.index(e) if e in l else None 

which works as follows:

 >>> a = ['a', 'b', 'c', 'g', 'c'] >>> test(a, 'b') 1 >>> test(a, 'c') 2 >>> test(a, 't') None 

So basically, test() will return the index of the element (second parameter) within the given list (first parameter) , if it was not found (in this case it will return None , but that may be all that you find suitable) .

+2
Nov 19 '11 at 21:18
source share

If you do not care where it is in the sequence, only its presence, then use the in operator. Otherwise, write a function that reorganizes the exception handling.

 def inlist(needle, haystack): try: return haystack.index(needle) except ...: return -1 
+1
Nov 19 '11 at 21:10
source share

hope this helps

 lst= ','.join('qwerty').split(',') # create list i='a' #srch string lst.index(i) if i in lst else None 
+1
Nov 19 2018-11-11T00:
source share

I like to use the List class for Web2py> found in the storage module of its gluon package. The storage module offers similar List and Dictionary structures that do not cause errors when an item is not found.

First download the web2py source , then copy the gluon package folder into your python installation package sites.

Now try:

 >>> from gluon.storage import List >>> L = List(['a','b','c']) >>> print L(2) c >>> print L(3) #No IndexError! None 

Note that it can also behave like a regular list:

 >>> print L[3] Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> l[3] IndexError: list index out of range 
0
Aug 28 '14 at 22:13
source share

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.

0
Dec 17 '17 at 18:33
source share

There is no built-in way to do what you want to do.

Here is a good post that can help you: Why does the list have no security "get" method, like a dictionary?

-one
Nov 19 '11 at 21:16
source share



All Articles