2

Why does '' and not '123' evaluate to '' instead of False, but not '123' and '' evaluates to False in Python 3.4.3?

1 Answer 1

2

The logical and/or operators stop evaluating terms (short-circuit) as soon as the answer is decided.

Examples with and

>>> '' and not '123'
''

The first one is false, so the and is short-circuited and the first one is returned.

>>> not '123' and ''
False

not '123' returns False. Since that is false, the and is short-circuited and the result of not '123' one is returned.

For exactly the same reason, the following returns zero:

>>> 0 and '123'
0

And the following returns []:

>>> [] and '123'
[]

Examples with or

>>> '' or '123'
'123'
>>> not '123' or 'Hi'
'Hi'
>>> '123' or 'Hi'
'123'

Documentation

This behavior is specified in the documentation where:

  • x or y is defined as if x is false, then y, else x

  • x and y is defined as if x is false, then x, else y

  • not x is defined as if x is false, then True, else False

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

3 Comments

All this time I thought Python returns the boolean value of the result.
So x or y or z or 0 works like COALESCE(x, y, z, 0) in SQL. Awesome.
Yes, similar. COALESCE looks for the first non-null while the python or looks for the first argument that does not evaluate to False. I just added a link to the docs which may help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.