if statement - Better way to check a list for specific elements - python -


i using try/except blocks substitute if/elif has bunch of ands. looking list , replacing elements if has x , x , x, etc. in project, have check upwards of 6 things drew me using try/except .index() throw error if element isn not present.

an analogy looks this:

colors = ['red', 'blue', 'yellow', 'orange']  try:     red_index = colors.index('red')     blue_index = colors.index('blue')     colors[red_index] = 'pink'     colors[blue_index] = 'light blue' except valueerror:     pass try:     yellow_index = colors.index('yellow')     purple_index = colors.index('purple')     colors[yellow_index] = 'amarillo'     colors[purple_index] = 'lavender' except valueerror:     pass 

so if colors array doesn't contain 'purple' 'yellow', don't want array change.

i bit wary of approach because seems abuse of try/except. shorter alternative because have grab elements' index anyway, know if there blatant problems or if crazy enough other developers hate me it.

that's not crazy; try/except pretty pythonic - see this question more discussion.

the other way is:

if 'red' in colours , 'blue' in colours:     colour[colours.index('red')] = 'pink'     # etc 

advantages on try/except:

  1. fewer lines of code if you're that
  2. much more readable - future reader know mean

disadvantages on try/except:

  1. slower (albeit totally negligible amount) since contains own search element.

unless you're doing requires extremely time efficient, i'd favour readability. however, try/except isn't unforgivable if have other reasons doing it.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -