DEV Community

Cover image for The Secret Life of Python: The Truth About Nothing
Aaron Rose
Aaron Rose

Posted on

The Secret Life of Python: The Truth About Nothing

The library was quiet, save for the rhythmic scratching of Timothy’s pen. He was debugging a function on his screen, cross-referencing it with his notes.

"Margaret," he said, looking up. "I think I’m getting the hang of this 'readability' thing. Look at how explicit I made these checks."

He spun the laptop around.

# Timothy's "Explicit" Code
def process_order(items, user_name):
    if len(items) > 0:
        print("Processing items...")

    if user_name != "":
        print(f"User is: {user_name}")

    if items is not None:
         # do something else

Enter fullscreen mode Exit fullscreen mode

"It’s very... thorough," Timothy beamed. "I’m checking everything. I check if the list length is greater than zero. I check if the string is not empty. I’m leaving nothing to chance."

Margaret peered over her spectacles. "It is certainly thorough, Timothy. But it is speaking Python with a heavy accent."

She reached for the keyboard. "In Python, we do not interrogate our objects with twenty questions. We simply ask them to weigh in."

The "Scale" of Truth

Margaret deleted Timothy’s verbose checks and replaced them with this:

# Margaret's "Pythonic" Code
def process_order(items, user_name):
    if items:
        print("Processing items...")

    if user_name:
        print(f"User is: {user_name}")

Enter fullscreen mode Exit fullscreen mode

Timothy frowned. "Wait. if items:? But items is a list, not a boolean. It’s not True or False. It’s a collection of things."

"Is it?" Margaret stood and walked to a vintage brass weighing scale sitting on the mantle.

"In Python," she began, "every object has a 'Truthiness.' It isn't just about the boolean True or False. It is about substance."

She placed a heavy book on one side of the scale. The scale tipped.
"This list has items. It has weight. Therefore, it is Truthy."

She removed the book, leaving the scale empty and balanced.
"This list is empty. It has no weight. Therefore, it is Falsy."

The "Whitespace" Trap

Timothy nodded slowly. "Okay. If it has substance, it's True. If it's empty, it's False."

He looked at his code again. "So if a user enters a space for their name—just hits the spacebar—that's empty, right? So if user_name: should be False?"

"Careful," Margaret warned. "Does air have weight?"

"Technically... yes."

"A string containing a space is not empty," Margaret corrected. "It contains a character: the space character. Therefore, it has weight."

She typed a quick demonstration to prove it.

name = " " # Just a space

if name:
    print("This name is Truthy!")
else:
    print("This name is Falsy!")

Enter fullscreen mode Exit fullscreen mode

Output:

This name is Truthy!

Enter fullscreen mode Exit fullscreen mode

Timothy looked alarmed. "That could be a bug. If I want to block users from having blank names, this check would let them through."

"Precisely," Margaret said. "This is one of the few times you must be explicit. If you want to check for 'substance' beyond just whitespace, you must strip the air away first: if name.strip():."

The Truthiness Audit

"This is getting slippery," Timothy said. "How do I know for sure what counts as 'nothing'?"

"We audit them," Margaret said. "We put them on the scale."

She wrote a script to loop through common "empty" values and check their official boolean status.

# The Truthiness Audit
suspects = [
    [],         # Empty List
    [1],        # List with item
    "",         # Empty String
    " ",        # String with space
    0,          # Zero
    1,          # Non-zero number
    None,       # The Void
    True,       # Boolean True
    False       # Boolean False
]

print(f"{'OBJECT':<10} | {'TRUTHINESS'}")
print("-" * 25)

for suspect in suspects:
    # The bool() function reveals the truth
    print(f"{repr(suspect):<10} | {bool(suspect)}")

Enter fullscreen mode Exit fullscreen mode

They ran the script. The evidence was undeniable.

OBJECT     | TRUTHINESS
-------------------------
[]         | False
[1]        | True
''         | False
' '        | True
0          | False
1          | True
None       | False
True       | True
False      | False

Enter fullscreen mode Exit fullscreen mode

The Trap of "None"

"Notice None," Margaret pointed out. "It evaluates to False, just like the empty list []. But be careful. An empty list is a box with nothing in it. None means there is no box."

"If you specifically need to know if the box is missing," she added, "you must ask explicitly: if items is None:."

"But for 99% of your logic," she concluded, "you don't need to measure the box or count the items. You just need to ask the object one question: Do you matter?"

She tapped the screen. "Besides, if items: is faster than calculating the length. You aren't just writing cleaner code, Timothy; you are writing faster code."

Margaret’s Cheat Sheet

Margaret opened her notebook to the "Logic" section.

  • Truthiness: You can use any object in an if statement.
  • The "Falsy" Club:
  • False
  • None (The Void)
  • 0 or 0.0 (Zero)
  • Empty collections: "", [], (), {}

  • The "Truthy" Club: Everything else.

  • The Whitespace Trap: " " is Truthy! If you need to ignore whitespace, use if string.strip():.

  • The Rule of Thumb: "If it’s empty or zero, it’s False. If it has contents, it’s True."


In the next episode, Margaret and Timothy will face "The Dangerous Reflection"—where a simple list assignment acts like a hall of mirrors.


Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.

Top comments (0)