Batu Lab NotesPractical developer guides

Report the index of a rejected sequence item

By Batu · English technical notes

To report the index of a rejected sequence item, iterate with enumerate() and include both the index and the value in the validation error. A boolean aggregate such as all(values) can tell this fixture that ['ok', '', 'later'] is not entirely truthy, but it cannot identify the empty string’s position in its result.

The first printed line is the deliberately insufficient result of all(values): False. The corrected validate_nonempty() function pairs each item with its zero-based index. It stops at the first falsy item and raises ValueError with a stable message containing index=1 and value=''. The except in the outer demonstration only turns that known validation result into deterministic stdout. Assertions check the original boolean observation and the exact diagnostic produced by the corrected implementation.

This is a first-rejection validator, not an all-errors collector. It does not inspect 'later' after the empty item causes the exception, and truthiness may not express every domain’s definition of valid input. For example, a numeric zero is falsy but might be valid. Replace if not value with a precise predicate when the data contract requires one. enumerate(iterable, start=0) is the standard built-in for producing index-and-value pairs, and its optional start parameter can be changed if a user-facing convention is one-based. enumerate documentation.

AI-assistance disclosure: This article was drafted with AI assistance and uses a synthetic in-memory sequence.

values = ["ok", "", "later"]


def validate_nonempty(items):
    for index, value in enumerate(items):
        if not value:
            raise ValueError(f"index={index} value={value!r}")


boolean_result = all(values)
assert boolean_result is False
print(f"boolean result: {boolean_result}")

try:
    validate_nonempty(values)
except ValueError as error:
    rejection = str(error)

assert rejection == "index=1 value=''"
print(f"rejected: {rejection}")
boolean result: False
rejected: index=1 value=''