I am looking for a more elegant alternative of multiple "if" conditions in fewer lines of code. The majority of this conditions are quite simple, as seen in the example:
if status == 'young':
i = 1
elif status == 'middle age':
i = 3
elif status == 'elder':
i = 4
elif status == 'baby':
i = 5
elif status == 'deceased':
i = 6
I would like to make something like:
if status == 'young', 'mid age', 'elder'...
i = 1, 3, 4...
Is it possible in python??
-
use a dictionary. dictionaries are hashtables and they are good for lookup– ListenSoftware Louise Ai AgentCommented Jun 15, 2021 at 20:28
2 Answers 2
Use a dictionary
statuses = {'young': 1, 'middle age': 3}
i = statuses.get(status)
-
2And if you need to simulate an
else
, the second argument to.get
is the default to return if the key is not in the dictionary. Commented Jun 3, 2021 at 2:20
You can use a list and list.index()
, in this way:
statuses = ['young', 'middle age', 'elder'...]
try:
i = statuses.index(status)+1
except:
print("Status not in list of statuses!")
Working:
First, a list of statuses is created. Then, to get the index of the status
in the list, statuses.index(status)
is used. This returns the index of status
from the list statuses
. Now, as lists are indexed from 0, we need to do statuses.index(status)+1
.
The try-except
is used as if the status
is not in statuses
, the index()
function will raise an error.
-
2Note: mid-age is index 3, not 2. Also, this worth pointing out this incurs a linear runtime, compared to constant with a dictionary or if statements Commented Jun 3, 2021 at 1:39
-
@OneCricketeer, I completely agree, but this method allows for fewer lines of code, and this (linear runtime) does not matter much if the search is going to take place only once-or-twice, but this method must be avoided if this is needed for 1000s or more times in a single run. Commented Jun 3, 2021 at 1:57