List comprehension if-else in one line | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

List comprehension if-else in one line

I'm shortening a code and trying to compress an if/else statement but I don't how to. This is what I have If opcn1 == 1: var1 = X Elif opcn1 == 2: Var1 = Y Elif opcn1 == 3: Var1 = Z Elif opcn1 == n... etc...

7th May 2020, 3:14 AM
John Larz
John Larz - avatar
2 Answers
+ 3
You can try this :)) var1 = X if opcn1 == 1 else Y if opcn1 == 2 else Z if opcn1 == 3 else .... Example : x = 1 y = 'one' if x == 1 else 'two' if x == 2 else 'idk' print(y) # one
7th May 2020, 3:23 AM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
0
You can use a tuple: Var1 = (None, X, Y, Z)[opcn1] https://code.sololearn.com/cKcgEYDfJ5Wi/?ref=app
7th May 2020, 4:14 AM
Bilbo Baggins
Bilbo Baggins - avatar