views:

629

answers:

3

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?

+5  A: 
if element in mylist:
    index = mylist.index(element)
    # ... do something
else:
    # ... do something else
Jerub
I like! Thanks!
jjnguy
I can't believe I tagged the question with java and pythin. Thanks for fixing it.
jjnguy
Of course, this will search through the list twice, and for long lists will be asymptotically twice as slow... But I wouldn't know a better solution.
Thomas
+9  A: 

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.

Kevin Little
Which way is faster? Or is that a irrelevant question? Should I be using C? ;)
jjnguy
@jinguy: don't worry about speed. Just write code that reads easily. If you need better performance, run it through a profile -- good chance the slow part is not exception handling.
John Millikin
Thanks for fixing the typo, John!
Kevin Little
@john, thanks for the advice
jjnguy
@jinguy, usually the EAFP has superior performance for the non-error case, which occurs more often (in most cases :) than the error case. YMMV depending on the details.
Kevin Little
A: 

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.

Brian