Handling
Empty Inputs
Learn to write resilient Python code that safely handles empty collections, missing values, and single-element edge cases.
What Are Empty Inputs?
An empty input is any data structure or value that contains no elements. In Python, these include empty lists [], empty strings "", empty dictionaries {}, and the special value None.
Why Empty Inputs Crash Code
Functions that assume at least one element exists will raise errors when given empty data. The most common crash is an IndexError from accessing an element that does not exist.
Python's Truthiness Rules
Python treats empty collections as falsy and non-empty ones as truthy. This is the foundation of safe empty-input handling.
The Guard Clause Pattern
A guard clause checks for empty or invalid input at the very top of a function and returns a safe default immediately, before any real logic runs.
The Single-Element Trap
Even when input is not empty, having only one element can break logic that assumes pairs or comparisons. A list of length \( 1 \) has no second element to compare against.
Empty vs Single-Element
| Empty Input | Single Element | |
|---|---|---|
| Example | [], "", None | [42], "a" |
| Typical error | IndexError, ZeroDivisionError | Wrong result, off-by-one |
| Detection | if not x |
if len(x) < 2 |
| Safe default | None, 0, [] | x[0] itself |
| Severity | Crash | Silent bug |
The Decision Flow
How to Apply the Pattern
None instead of a collection, guard against it first.if not items to catch empty lists, strings, dicts, and sets in one test.if len(items) < 2.None, 0, [], or the single element itself.Example 1: Safe Average
Computing the average of a list requires dividing by its length. If the list is empty, \( \text{len} = 0 \) causes a ZeroDivisionError.
Example 2: Finding the Min and Max
Python's built-in min() and max() raise ValueError on empty sequences. We need explicit guards.
Example 3: Consecutive Differences
Computing differences between consecutive pairs requires at least two elements. This is where single-element handling is critical.
Beyond Lists: Strings and Dicts
The same pattern applies to every collection type in Python. Empty strings and empty dicts are equally dangerous.
"".split() returns []. Indexing ""[0] raises IndexError. Guard with if not s.{}["key"] raises KeyError. Use dict.get(key, default) or guard with if not d.Using Default Parameters Safely
A common Python trap is using a mutable default argument. This creates a shared object across calls, leading to subtle bugs.
Common Mistakes
len(None) raises TypeError. Check for None before checking length.if x == [] only catches lists, missing empty tuples, strings, and sets. Use if not x.None when the caller expects a list causes downstream crashes. Match the expected type.Quick Reference Table
| Scenario | Guard Code | Safe Default |
|---|---|---|
| Input might be None | if x is None |
Return None or [] |
| Empty list / string | if not x |
Return 0, "", or [] |
| Single element | if len(x) < 2 |
Return x[0] itself |
| Dict key missing | d.get(k, default) |
The default value |
| Mutable default arg | param=None |
Create [] inside function |
Question 1 of 5
What does bool([]) return in Python?
bool([]) returns False, just like bool(""), bool({}), and bool(0).Question 2 of 5
Code:
def process(items):
first = items[0]
last = items[-1]
return first + last
What error occurs when process([]) is called?
items[0] on an empty list raises IndexError: list index out of range. A guard clause like if not items: return None would prevent this crash.Question 3 of 5
Which is the most Pythonic way to check if a list is empty?
if not items because it leverages Python's truthiness, is shorter, and works for any empty collection type: lists, strings, dicts, sets, and tuples.Question 4 of 5
Code:
def avg(nums):
if not nums:
return 0
return sum(nums) / len(nums)
result = avg([5])
What is the value of result?
[5] is not empty, so the guard clause is skipped. Then \( \frac{5}{1} = 5.0 \). Division in Python 3 always returns a float, so the result is 5.0, not the integer 5.Question 5 of 5
Code:
def safe_max(nums):
if nums is None:
return None
if not nums:
return None
return max(nums)
Why does this function check is None separately before not nums?
not None is True (so the second check would catch it), separating the checks makes the code self-documenting. It signals to readers that you intentionally handle two distinct cases: no argument passed vs. an empty collection passed.