Question

I have this code:

chars = #some list

try:
    indx = chars.index(chars)
except ValueError:
    #doSomething
else:
   #doSomethingElse

I want to be able to do this because I don't like knowfully causing Exceptions:

chars = #some list

indx = chars.index(chars)

if indx == -1:
    #doSomething
else:
   #doSomethingElse

Is there a way I can do this?

Was it helpful?

Solution

Note that the latter approach is going against the generally accepted "pythonic" philosophy of EAFP, or "It is Easier to Ask for Forgiveness than Permission.", while the former follows it.

OTHER TIPS

if element in mylist:
    index = mylist.index(element)
    # ... do something
else:
    # ... do something else

For the specific case where your list is a sequence of single-character strings you can get what you want by changing the list to be searched to a string in advance (eg. ''.join(chars)).

You can then use the .find() method, which does work as you want. However, there's no corresponding method for lists or tuples.

Another possible option is to use a dictionary instead. eg.

d = dict((x, loc) for (loc,x) in enumerate(chars))
...
index = d.get(chars_to_find, -1)  # Second argument is default if not found.

This may also perform better if you're doing a lot of searches on the list. If it's just a single search on a throwaway list though, its not worth doing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top