Logical operators in Python

that is well documented:

x or y      if x is false, then y, else x 
x and y     if x is false, then x, else y 

both short-circuit (e.g. or will not evaluate y if x is truthy).

the documentation also states what is considered falsy (False, 0, None, empty sequences/mappings, …) – everything else is considered truthy.

a few examples:

7 and 'a'             # -> 'a'
[] or None            # -> None
{'a': 1} or 'abc'[5]  # -> {'a': 1}; no IndexError raised from 'abc'[5]
False and 'abc'[5]    # -> False; no IndexError raised from 'abc'[5]

note how the last two show the short-circuit behavior: the second statement (that would raise an IndexError) is not executed.

your statement that the operands are boolean is a bit moot. python does have booleans (actually just 2 of them: True and False; they are subtypes of int). but logical operations in python just check if operands are truthy or falsy. the bool function is not called on the operands.


the terms truthy and falsy seem not to be used in the official python documentation. but books teaching python and the community here do use these terms. there is a discussion about the terms on english.stackexchange.com and also a mention on wikipedia.

Leave a Comment