Skip to main content

Command Palette

Search for a command to run...

Ors & Ands

Updated
1 min read
Ors & Ands

I came across Stephen Grupetta’s article that highlights a nuance that I didn’t consider. or and and don't return booleans. They return one of their operands which can be any data type.

The Rules

or:

  • Returns the first operand when it's truthy

  • Returns the second operand when the first is falsy

and:

  • Returns the first operand when it's falsy

  • Returns the second operand when the first is truthy

Python objects are either truthy or falsy, it doesn't matter that or and and don't return Booleans! Leverage this to short circuit on assignment for idiomatic code and avoid a gotcha

Happy Hackin’

References