python - Grab following index from tuple: 2 try/except or 1 if/elif -
couldn't find information on try vs. if when you're checking more 1 thing. have tuple of strings, , want grab index , store index follows it. there 2 cases.
mylist = ('a', 'b')
or
mylist = ('y', 'z')
i want @ a
or y
, depending on exists, , grab index 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, think may better/more efficient write way, since half time, raise exception, (valueerror
), more expensive 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 right in assumption if
better/more efficient here? or there better way of writing entirely i'm unaware of?
well opinion close rohith subramanyam's. think loop more readable, in case have more 2 elements test !
but still think if block far more logical use (pun intended!). strictly speaking less redundant in terms of lines of code:
accepted_elements = ['a', 'y'] item['index'] = none accepted_element in accepted_elements: if accepted_element in mylist: item['index'] = mylist[mylist.index(accepted_element) + 1] break
i think solution use in end you, depends on code habits (except loop must).
edit: actually, after time measurements seems rohith subramanyam's version faster @ first sight. (640 ns per loop vs 740 ns per loop)
Comments
Post a Comment