Python how to shorten If else condition

Question:

How can I shorten this condition pattern;

if xconditon == "a text":
 Avariable = Yvariable

elif xcondition == "b text":
 Bvariable = Yvariable

elif xcondition == "c text":
 Cvariable = Yvariable

condition goes on like this, there is a pattern so I am searching for ways to shorten this code.

I’m looking for best way to reduce the code clutter, also improving the performance, looked for Python equivalent C++ auto, thought of using 2D lists but using dictionary seems better.

Asked By: RisenShadow

||

Answers:

Don’t use different variables, use a dictionary.

mydict[xcondition] = Yvariable
Answered By: Barmar

You could loop through the list of conditions and their corresponding variable names if you really have a lot of them, for just three it doesnt make sense though. I made an example:

list = [
"a":{"letter":"a","condition":"conditionA", variable:"variableA"}
"b":{"letter":"b","condition":"conditionB", variable:"variableB"}
]

for i in list:
    if conditionX == i["condition"]:
        list["letter"]["variable"] = variableX
Answered By: Sven Asmussen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.