4

Can somebody explain the reasoning behind the following tests ??

>>> 1 and True
True
>>> {'foo': 'Foo'} and True
True
>>> {} and True
{}
>>>
MrSmith42
  • 9,961
  • 6
  • 38
  • 49
simplyharsh
  • 35,488
  • 12
  • 65
  • 73
  • Related question: http://stackoverflow.com/questions/3826473/boolean-operations-in-python-ie-the-and-or-operators – tzot Dec 05 '10 at 20:12

2 Answers2

8

Python doesn't have a boolean and or boolean or. Its and and or operators are coalescing, which means that they return the first non-true or true operand, or the second operand.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
5

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

For further reference read more on Boolean operations: http://docs.python.org/reference/expressions.html#boolean-operations

meson10
  • 1,934
  • 14
  • 21