The Unexpected Boolean of Empty Lists in Lists

Posted by Afsal on 06-Dec-2024

In Python, the concept of "truthiness" can sometimes lead to surprising behavior, especially when dealing with nested lists that include empty lists. Let’s dive into this quirky behavior and understand it better.

Boolean Basics in Python

Python evaluates objects for their "truthiness" in a logical context:

Truthy: Non-zero numbers, non-empty strings, lists, etc.

Falsy: None, 0, False, empty sequences like [], (), and {}.

Code

>>> print(bool([])) 
False
>>> print(bool([1, 2, 3]))  
True
>>>

But what happens when you deal with lists containing empty lists?

The Unexpected Case

code

>>> nested_list = [[], [], []]
>>> print(bool(nested_list))

What’s your guess? Surprisingly:

The result is True, even though all the inner lists are empty!

Why?

This happens because:

An empty list ([]) is False in a boolean context.

However, a non-empty list—even if it contains only empty lists—is True.

In the example above, nested_list itself is a list with three elements (all empty lists). Since it is non-empty, it evaluates to True.

>>> empty_list = []
>>> bool(empty_list)
False
>>> nested_list = [[], [], []]
>>> bool(nested_list)
True
>>> another_nested_list  = [[], [1], []]
>>> bool(another_nested_list)
True
>>> 

Even though nested_list contains empty lists, the presence of any non-empty inner list ensures the whole list is True.

Common Pitfalls

Checking for "All Empty" Lists: You might mistakenly assume bool(nested_list) will be False if the inner lists are empty. Instead:

>>> nested_list = [[], [], []]
>>> bool(nested_list)
True
>>> another_nested_list  = [[], [1], []]
>>> bool(another_nested_list)
True
>>> 
>>> all(nested_list)
False
>>> any(nested_list)
False
>>> all(another_nested_list)
False
>>> any(another_nested_list)
True
>>> 

Practical Applications

This behavior often arises in real-world scenarios, such as:

Processing Nested Data Structures: Handling JSON or XML data where some lists may be empty.

Input Validation: Ensuring a list of fields isn’t empty.

Key Takeaways

An empty list ([]) evaluates to False.

A non-empty list, even if it only contains empty lists, evaluates to True.

Use function like all() and any() for nuanced checks on nested structures.

Python’s truthiness behavior is simple yet nuanced. Understanding it can help you avoid subtle bugs and write more predictable code.