Search code examples
pythonif-statementtry-except

Better way to check a list for specific elements - python


I am using try/except blocks as a substitute for if/elif that has a bunch of ands. I am looking into a list and replacing some elements if it has x and x and x, etc. In my project, I have to check for upwards of 6 things which drew me to using the try/except with .index() which will throw an error if the element isn not present.

An analogy looks like 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 the colors array doesn't contain 'purple' as well as 'yellow', I don't want the array to change.

I am a bit wary of this approach because it seems like abuse of try/except. But it is much shorter than the alternative because I would have to grab the elements' index anyway, so I would like to know if there are blatant problems with this or if this is crazy enough that other developers would hate me for it.


Solution

  • That's not crazy; try/except is pretty pythonic - see this question for more discussion.

    The other way you could do this is:

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

    Advantages over try/except:

    1. Fewer lines of code if you're into that
    2. Much more readable - any future reader would immediately know what you mean

    Disadvantages over try/except:

    1. Slower (albeit by a totally negligible amount) since contains will do its own search for the element.

    Unless you're doing something that requires this to be extremely time efficient, I'd favour readability. However, the try/except isn't unforgivable if you have other reasons for doing it.