Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Pick other value

Tags:

python

list

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.

like image 598
Oli Avatar asked Dec 16 '22 14:12

Oli


2 Answers

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]]
like image 110
Sven Marnach Avatar answered Dec 31 '22 05:12

Sven Marnach


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]
like image 31
Bryce Siedschlaw Avatar answered Dec 31 '22 06:12

Bryce Siedschlaw