Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Kevin Ohlsson
Kevin Ohlsson
4,547 Points

What's the 'philosophical' reason why something empty returns false and something that holds data returns true?

Kenneth introduced the python basic 3 chapter with 'philosophical discussions aside...'.

This made me keen to ask if there some other programming language than python were something 'empty' returns true and something that holds data returns false? Or does this just not make any sense to do?

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,989 Points

The short answer is convenience. When using the "truthiness" of an object, the code reads smoothly

dic = {}
if dic:
    print("True")
else:
    print("False")

In implementation, object.__bool__() is "[c]alled to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, len() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither len() nor bool(), all its instances are considered true." source doc

A summary of the truth value testing of standard object:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a bool() or len() method, when that method returns the integer zero or bool value False

All other values are considered true — so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

I can't think of other programming languages where this would be reversed.