Fixing ValueError: max() arg is an empty sequence

Empty iterable ValueError and missing max() candidates in Python

Find the iterable passed to max() and determine why it has no items. Python raises a ValueError when max() receives an empty iterable without a default; the right fix depends on whether that absence is expected or a broken assumption.

max() arg is an empty sequence: what happened?

In ValueError: max() arg is an empty sequence, “sequence” describes the immediate problem, but the input need not be a list. A generator, filter object, or another iterable can also produce no values. Python cannot select the largest item from a collection with no candidates. Exception wording varies by Python version: a newer interpreter may report max() iterable argument is empty instead.

scores = []
max(scores)  # raises ValueError

The Python documentation for max() specifies that an empty iterable raises ValueError unless the keyword-only default is supplied. For a nonempty iterable, max() returns the largest item. With key, it compares the results of a function but returns the original item, not the comparison value.

Start at the traceback line that calls max() and trace its input backward. For a list, inspect its length and a small sample. If it came from a query or a filter, inspect both the original input and the conditions that select items. A full table may still yield an empty result for a particular date, account, or status. If an empty iterable causes a max ValueError only for one request, log the request parameters along with the number of rows returned. That makes an over-restrictive date range easier to distinguish from an import that produced no rows at all.

Keep a broken contract visible

Suppose an upstream process promises at least one score for every completed match. In that case, an empty list is evidence that something earlier went wrong. Replacing the result with zero would hide that evidence and could make an incomplete match look like a valid low score.

def winning_score(scores):
    if not scores:
        raise ValueError("A completed match must have at least one score")
    return max(scores)

print(winning_score([3, 8, 5]))  # 8

The check adds context: the failure now names the violated rule. The exception still stops the calculation. Without the explicit check, max raises a ValueError on the empty input; with it, the message identifies the contract that failed. In a larger application, catch it at a boundary that can report or handle an invalid match, rather than silently returning an invented score. This list-specific check is appropriate because an empty list is false; do not assume an arbitrary generator behaves the same way.

For example, ValueError: max() arg is an empty sequence may be the first sign that a data import skipped every row. Inspect the import count and rejected rows before changing the maximum calculation. The exception points to where the absence became impossible to ignore; its cause may be much earlier. A ValueError from max on empty data can result when every CSV row is rejected for a missing required field.

Give an empty result a meaning

If no scores is a valid outcome, express that in the return value. A list allows a direct check before selecting the maximum:

def highest_score(scores):
    if not scores:
        return None
    return max(scores)

print(highest_score([]))       # None
print(highest_score([0, 4]))   # 4

The caller can distinguish None from a real score of zero with result is None. Do not use if not result for that distinction: zero is false too. Document the return type and make the caller decide what “no scores” means, perhaps displaying “No results yet” instead of a number. This branch prevents max from raising a ValueError for an empty score list while preserving the difference between missing data and zero.

For the iterable form of max(), the same policy can be concise:

scores = []
best = max(scores, default=None)
print(best)  # None

The default is returned only when the iterable produces no items. It is not included as a candidate in the comparison. This approach turns an empty maximum input into a deliberate result instead of a ValueError, provided the caller handles that result. Thus max([-7, -2], default=0) returns -2, not 0. Pick a fallback that means something in the application. Zero can be a sensible answer for an empty count in a particular model, but it is misleading if “no observation” must remain distinct from an observed zero.

A fallback also prevents the empty-input ValueError from max(); it does not repair incompatible items or exceptions raised by a key function. For instance, a mixture of integers and strings cannot generally be ordered with max() in Python 3. Treat those as separate data problems, not as empty-input cases.

Filtering can remove every candidate

A filter can be perfectly valid and still leave nothing to compare. In this example, the threshold excludes every measurement, so the result is explicitly absent rather than an exception from an empty call to max():

readings = [12, 18, 21]
qualifying = [value for value in readings if value >= 25]
best = max(qualifying, default=None)
print(qualifying, best)  # [] None

If the absence is surprising, inspect the threshold, units, and incoming values. A maximum over an empty filtered iterable raises ValueError without the fallback, even when the original readings list contains many items. Perhaps the data is in Celsius while the threshold assumes Fahrenheit, or the comparison should include a boundary value. A list comprehension makes the intermediate result visible, which is convenient when the result set is small enough to store.

For larger streams, a generator expression avoids building that intermediate list. The same default handles a stream with no qualifying values:

readings = [12, 18, 21]
best = max((value for value in readings if value >= 18), default=None)
print(best)  # 21

If a generator-based maximum raises an empty-input ValueError, inspect how the stream is created and consumed. Do not print list(stream) and then pass that same stream to max() expecting the original items to remain. Either recreate the generator or save the materialized list and use that list for the calculation.

Look for an already consumed generator

A generator is an iterator: once its items have been read, another pass over that same object has no values left. The Python glossary distinguishes an exhausted iterator from a container such as a list, which can produce a fresh iterator for each pass. A truth test like if stream does not establish whether a generator has remaining items.

stream = (number for number in [2, 5, 9])
print(list(stream))             # [2, 5, 9]
print(max(stream, default=None))  # None

values = [2, 5, 9]
print(max(values))              # 9

A diagnostic print, a prior loop, or an earlier aggregation can consume the stream. If the next call reports ValueError: max() arg is an empty sequence or its newer equivalent, find the first consumer in the traceback’s surrounding code. For a small dataset, materialize once and reuse the list; for a large or one-pass source, perform the required work in one pass or construct a fresh stream from a repeatable source. If the data really is absent, apply the contract or fallback policy rather than repeatedly recreating an empty generator.