0

This seems like a simple question but I was unable to find a precedent. One answer here points it out without explaining why.

Using logical operators without two variables returns not a boolean but one of the variables - the first for OR and the second for AND.

'x' or 'y'
> 'x'

3 and 4
> 4

What's the reason for this behaviour?

1
  • Make your code shorter. 'x' or 'y' is shorter than 'x' if 'x' else 'y' Commented Apr 18, 2019 at 8:25

1 Answer 1

4

The reason is that that is the most efficient way to shortcut evaluation of boolean expressions. With or Python returns the first truthy value that it encounters. It doesn't need to evaluate the rest to discover if the expression is true. Similarly, with and Python returns the first falsy value that it encounters. It doesn't need to evaluate the rest to discover if the expression is false.

If it bothers you that you get a non-boolean back, then wrap a call to bool() around your expression.

Sign up to request clarification or add additional context in comments.

6 Comments

Both 3 and 4 are truthy, though
@alec_a not in the boolean context of 3 and 4.
Yes, but for and it returns the first falsy value. You can't tell if the expression is true without evaluating everything.
@lucasgcb What do you mean, not in the boolean context? if 3 returns True
@JoshFriedlander I take your point but the behaviour has been there since Python 1 (before Python even had a boolean type) and there is a lot of code out there that expects to get the last value back from and, so it would be hugely disruptive to change that now.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.