1

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??

asked Jun 3, 2021 at 1:30
1

2 Answers 2

11

Use a dictionary

statuses = {'young': 1, 'middle age': 3}
i = statuses.get(status)
answered Jun 3, 2021 at 1:33
1
  • 2
    And 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
0

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.

answered Jun 3, 2021 at 1:36
2
  • 2
    Note: 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.
    CoolCoder
    Commented Jun 3, 2021 at 1:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.