I have found that the following code works like the conditional operator in Python.
num1 = condition and val1 or val2
Could I use it in place of the following?
num1 = val1 if condition else val2
Makoto
107k29 gold badges200 silver badges236 bronze badges
asked Oct 20, 2018 at 16:09
Jeyakeethan Geethan
792 silver badges8 bronze badges
-
1...why would you want to use that unreadable thing instead of a conditional?Aran-Fey– Aran-Fey2018年10月20日 16:11:42 +00:00Commented Oct 20, 2018 at 16:11
-
you can do it, but it is not python wayAndrei Berenda– Andrei Berenda2018年10月20日 16:38:35 +00:00Commented Oct 20, 2018 at 16:38
3 Answers 3
The first code you propose does not behave always as the second since, here a counter example where condition is true, val1 is 0 and val2 is 2
num1 = True and 0 or 2
num1 is equal to 2 after the assignment because 0 is evaluated as false in the context of a logical expression. In the second code the result would be 0 instead.
answered Oct 20, 2018 at 16:16
Marco
1731 gold badge1 silver badge5 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
I would advise you against it for two reasons.
- If conditional statement clearly conveys your intent, which helps with readability of your code.
- That behaviour may not be consistent across different python versions (past or future) and you risk breaking your code in very subtle ways if you use this.
Comments
No you can't. It won't work correctly if val1 is falsy:
>>> 0 if True else 1
0
>>> True and 0 or 1
1
answered Oct 20, 2018 at 16:15
Aran-Fey
44.1k13 gold badges113 silver badges161 bronze badges
Comments
lang-py