ValueError: max() arg is an empty sequence
ValueError: max() arg is an empty sequence in Python means max() and min() have no answer for an empty list, so they raise. Give them a default, or handle the empty case first.
How do I fix ValueError: max() arg is an empty sequence?
ValueError: max() arg is an empty sequence means you called max() or min() on an empty list, filter or generator. Python 3.12 and later say "max() iterable argument is empty". Pass a fallback with the default= argument, for example max(scores, default=0), or check if scores: before calling it.
- 1. Print the inputPrint the list or list(generator) just before max(). Confirm it really is empty.
- 2. Add default=Write max(items, default=0) or min((p for p in prices if p > budget), default=None).
- 3. Check the filterIf the list should not be empty, the condition in the comprehension or the data loading is the real bug.
What does ValueError: max() arg is an empty sequence mean?
There is no largest item in nothing. Python 3.12 and later word it "max() iterable argument is empty"; older versions say "max() arg is an empty sequence". Both mean the list, filter or generator you passed had no items.
Why does ValueError: max() arg is an empty sequence happen?
1. No data yet
New users, new products and empty days all produce empty lists.
Breaks
best = max(scores)Works
best = max(scores, default=0)2. A filter that matched nothing
The generator is empty when no item passes the condition.
Breaks
cheapest = min(p for p in prices if p > budget)Works
cheapest = min((p for p in prices if p > budget), default=None)3. max() with a key over an empty dictionary
The same rule applies to dictionaries.
Breaks
top = max(counts, key=counts.get)Works
top = max(counts, key=counts.get) if counts else NoneHow to find it in your own code
Decide what an empty input should mean (0, None, a message) and pass it as default=. Then check why it was empty: no data yet is expected, but an empty list from a wrong filter is the real bug.
Try it: fix this bug
easyfind_top_score([]) raises ValueError: max() arg is an empty sequence.
def find_top_score(scores):
return max(scores)More challenges with this error
Each of these challenges runs into this error. Find the bug and fix it, no install and no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.