🕯️ Magic Note
The min() function normally raises a ValueError when called on an empty iterable. The default parameter changes this behavior. When the iterable is empty, min() returns the default value instead of throwing an error. This turns a crash into a graceful silence.
- The default parameter works in both min() and max() functions
- Available from Python 3.4 onwards
- Prevents ValueError: min() arg is an empty sequence
- Can use any default value, not just None
This is especially useful when filtering data that might return no results. Common defaults include 0, “”, False, or a custom sentinel value like “no match”.
| Input String | Generator Result | min() with default |
|---|---|---|
| “magic” | No repeating chars | None |
| “python” | No repeating chars | None |
| “hello” | “h”, “l” | “h” |
| “mississippi” | “m”, “i”, “s”, “p” | “i” |
| “aa” | “a” | “a” |
Python
# Safe min() with default
s = “unique”
dupe = min((c for c in s if s.count(c)>1), default=None)
print(dupe)
# Output: None
# No ValueError, just silence
Python
# Without default (dangerous)
s = “unique”
try:
dupe = min(c for c in s if s.count(c)>1)
except ValueError as e:
print(f”Spell failed: {e}”)
# Output: Spell failed: min() arg is an empty sequence
Python
# Using a custom default value
s = “no repeats here”
dupe = min((c for c in s if s.count(c)>1), default=”silence”)
print(dupe)
# Output: “silence” (depending on actual repeats in the string)
- Forgetting the default parameter exists and handling empty sequences with try/except instead
- Using default in Python versions older than 3.4, causing a TypeError
- Assuming min() with default is always the best choice, sometimes an explicit check is more readable
⚡ Whisper
A spell that crashes in silence is no spell at all. The default is your safety net. It catches nothing and returns peace. Even when there is no echo, the magic still completes.