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:
- fewer lines of code if you're that
- much more readable - future reader know mean
disadvantages on try/except:
- slower (albeit totally negligible amount) since
containsown 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
Post a Comment