0

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
2
  • 1
    ...why would you want to use that unreadable thing instead of a conditional? Commented Oct 20, 2018 at 16:11
  • you can do it, but it is not python way Commented Oct 20, 2018 at 16:38

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

I would advise you against it for two reasons.

  1. If conditional statement clearly conveys your intent, which helps with readability of your code.
  2. 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.
answered Oct 20, 2018 at 16:13

Comments

2

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

Comments

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.