01 / 21

Handling
Empty Inputs

Learn to write resilient Python code that safely handles empty collections, missing values, and single-element edge cases.

Python

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.

[] Empty List
A list with zero elements: \( \text{len}(\text{list}) = 0 \)
"" Empty String
A string with no characters at all
None No Value
Represents the absence of any value

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.

def get_first(items): return items[0] # IndexError if items is [] result = get_first([]) # Boom!

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.

Falsy [] "" {} set() 0 None False bool(...) returns False if not items: ... Triggers the guard clause Truthy [1, 2] "hi" {1:2} 42 True bool(...) returns True if items: ... Proceeds safely

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.

def get_first(items): if not items: # Guard clause return None # Safe default return items[0] # Now safe to index

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.

def find_max_diff(nums): # Wants to compare pairs, but what if len(nums) == 1? max_d = 0 for i in range(len(nums) - 1): max_d = max(max_d, abs(nums[i] - nums[i+1])) return max_d find_max_diff([42]) # Returns 0 -- correct here, but fragile

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

Function called is None? Yes Return None No
\( \text{len} == 0\text{?} \)
Yes Return default No
\( \text{len} == 1\text{?} \)
Yes Handle edge No Main logic

How to Apply the Pattern

1
Check for None. If your function might receive None instead of a collection, guard against it first.
2
Check for empty. Use if not items to catch empty lists, strings, dicts, and sets in one test.
3
Check for single element. If your logic needs \( n \geq 2 \) elements, add if len(items) < 2.
4
Return a meaningful default. Choose None, 0, [], or the single element itself.
5
Proceed with main logic. After all guards pass, your code can safely assume \( n \geq 2 \).

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.

def safe_average(nums): if not nums: # Guard: empty list return 0.0 return sum(nums) / len(nums) safe_average([]) # 0.0 (no crash) safe_average([10]) # 10.0 (single element works) safe_average([4, 6]) # 5.0 (normal case)

Example 2: Finding the Min and Max

Python's built-in min() and max() raise ValueError on empty sequences. We need explicit guards.

def min_max(nums): if not nums: return (None, None) # No data: safe tuple if len(nums) == 1: return (nums[0], nums[0]) # Same element is both return (min(nums), max(nums)) min_max([]) # (None, None) min_max([7]) # (7, 7) min_max([3, 1, 9]) # (1, 9)

Example 3: Consecutive Differences

Computing differences between consecutive pairs requires at least two elements. This is where single-element handling is critical.

def consecutive_diffs(nums): if not nums: return [] # No input: no diffs if len(nums) < 2: return [] # One element: no pairs return [nums[i+1] - nums[i] for i in range(len(nums) - 1)] consecutive_diffs([]) # [] consecutive_diffs([5]) # [] consecutive_diffs([1, 4, 2]) # [3, -2]

Beyond Lists: Strings and Dicts

The same pattern applies to every collection type in Python. Empty strings and empty dicts are equally dangerous.

Strings
"".split() returns []. Indexing ""[0] raises IndexError. Guard with if not s.
Dicts
{}["key"] raises KeyError. Use dict.get(key, default) or guard with if not d.
def first_word(text): if not text or not text.strip(): return "" return text.split()[0]

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.

# WRONG: mutable default argument def append_to(item, lst=[]): lst.append(item) return lst # CORRECT: use None sentinel def append_to(item, lst=None): if lst is None: lst = [] lst.append(item) return lst

Common Mistakes

✕ Checking len() on None
Calling len(None) raises TypeError. Check for None before checking length.
✕ Using == [] instead of not
Writing if x == [] only catches lists, missing empty tuples, strings, and sets. Use if not x.
✕ Forgetting return type
Returning 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?

Question 2 of 5

What error occurs when process([]) is called?

Question 3 of 5

Which is the most Pythonic way to check if a list is empty?

Question 4 of 5

What is the value of result?

Question 5 of 5

Why does this function check is None separately before not nums?