Python Tips and Gotchas #4 - Understand truthy and falsy

Truthy and falsy are the ways values implicitly converts to booleans when used in if-expressions, and are different to the booleans True and False. Booleans work pretty much identical in every major programming language. But the workings of truthy and falsy are not. Javascript are infamous for being really messy and inconsistent with its truthy and falsy values, while Swift and C# simply does not allow any implicit conversion to booleans. Python sits somewhere in between with a very rational and sensible arrangement.

When evaluated in if-expressions, the following values will evaluate to False:

  • False
  • None
  • 0 (integer)
  • 0.0 (float)
  • 0j (complex)
  • Decimal(0)
  • Fraction(0, 1)
  • [] (empty list)
  • {} (empty dict)
  • () (empty tuple)
  • set() (empty set)
  • ” (empty string)
  • b” (empty bytestring)
  • any empty range, like range(0) or range(0, 0)
  • objects with an implementation of bool() that returns False
  • objects with an implementatino of len() that returns 0

New Python developers with a background in Javascript or PHP should note that there is no such thing as loosely comparissons in Python. So while you in Javascript can do this:

1
2
3
4
> '' == false
true
> '' === false
false

And in PHP:

1
2
3
4
php > if('' == false) { echo 'false';  }
false
php > if('' === false) { echo 'false';  }
php > 

But Python does not work the same way, there is only strict comparisson that compares both value and type:

1
2
3
4
>>> '' == False
False
>>> '' == True
False