I am using try/except
blocks as a substitute for if/elif
that has a bunch of and
s. 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.
The any() function is used to check the existence of an element in the list. it's like- if any element in the string matches the input element, print that the element is present in the list, else, print that the element is not present in the list. Example: Python3.
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:
Disadvantages over try/except:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With