Please excuse (or improve the title) but I have a silly little problem that's making me very unsure.
I have a list that can contain one to two values, never more, never less and only these two options:
options = ['option one', 'option two']
As I say, sometimes there may only be one of those values in the list so it might just be ['option two',]
The scope for this is simple navigation on a website. I accept a querystring entrance and search the list for those options:
current_option = request.GET.get('option', options[0])
if not current_option in options: current_option = options[0]
If no "option" is provided, it defaults to the first available option.
But now I want to know what the other option is. If "option one"
is the input, I want "option two"
. And if there is only "option one"
in the options
list, for example, I want the return to be False
.
I know I can loop through the list but it feels like there should be a better way of just picking the other value.
options.remove(current_option)
options.append(False)
return options[0]
Edit: If you don't want to modify options
, you can also use the somewhat less readable
return (options + [False])[current_option == options[0]]
current_option = request.GET.get('option', options[0])
if not current_option in options:
current_option = options[0]
else:
oindex = options.index(current_option)
other_option = False if len(options) != 2 else options[(oindex+1) % 2]
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