Markus Meskanen Markus Meskanen - 7 months ago 10
Python Question

Python 3 and-or vs if-else

Is there any difference between the following?

print(x if x else 'no x available')
# compared to:
print(x and x or 'no x available')

Answer

In practice they are the same; in theory they are different, but only when the __bool__ method has side effects:

>>> class Weird:
    state = False
    def __bool__(self):
        self.state = not self.state
        return self.state


>>> x = Weird(); print(x if x else 'no x available')
<__main__.Weird object at 0x0000000003513160>
>>> x = Weird(); print(x and x or 'no x available')
no x available

If you run into this theoretical case you have worse problems to worry about.

Also note that:

>>> x = Weird(); print(x or 'no x available')
<__main__.Weird object at 0x00000000035071D0>

so Klass Ivan's answer is technically wrong.

Bottom line, use the if expression as that expresses what you mean much more clearly.