Couldn't find much information on try vs. if when you're checking more than one thing. I have a tuple of strings, and I want to grab an index and store the index that follows it. There are 2 cases.
mylist = ('a', 'b')
or
mylist = ('y', 'z')
I want to look at a
or y
, depending on which exists, and grab the index that follows. Currently, I'm doing this:
item['index'] = None
try:
item['index'] = mylist[mylist.index('a') + 1]
except ValueError:
pass
try:
item['index'] = mylist[mylist.index('y') + 1]
except ValueError:
pass
After reading Using try vs if in python, I think it may actually be better/more efficient to write it this way, since half the time, it will likely raise an exception, (ValueError
), which is more expensive than an if/else, if I'm understanding correctly:
if 'a' in mylist:
item['index'] = mylist[mylist.index('a') + 1]
elif 'y' in mylist:
item['index'] = mylist[mylist.index('y') + 1]
else:
item['index'] = None
Am I right in my assumption that if
is better/more efficient here? Or is there a better way of writing this entirely that I'm unaware of?