TheAlgorithms/Python · error · ValueError

abs_min() arg is an empty sequence

Error message

abs_min() arg is an empty sequence

What it means

Raised by abs_min in maths/abs.py when called with an empty list. The function scans for the element with the smallest absolute value; with no elements there is no answer, so it raises ValueError mirroring builtin min()'s error style ('abs_min() arg is an empty sequence').

Source

Thrown at maths/abs.py:30

    >>> abs_val(0)
    0
    """
    return -num if num < 0 else num


def abs_min(x: list[int]) -> int:
    """
    >>> abs_min([0,5,1,11])
    0
    >>> abs_min([3,-10,-2])
    -2
    >>> abs_min([])
    Traceback (most recent call last):
        ...
    ValueError: abs_min() arg is an empty sequence
    """
    if len(x) == 0:
        raise ValueError("abs_min() arg is an empty sequence")
    j = x[0]
    for i in x:
        if abs_val(i) < abs_val(j):
            j = i
    return j


def abs_max(x: list[int]) -> int:
    """
    >>> abs_max([0,5,1,11])
    11
    >>> abs_max([3,-10,-2])
    -10
    >>> abs_max([])
    Traceback (most recent call last):
        ...
    ValueError: abs_max() arg is an empty sequence
    """

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check for emptiness before calling: if not values: handle the empty case explicitly.
  2. Fix the upstream filter so it cannot produce an empty list when at least one element is expected.
  3. If an empty input is valid in your domain, define a sentinel (e.g. None or 0) instead of calling abs_min.

Example fix

# before
m = abs_min(filtered)  # filtered may be []

# after
m = abs_min(filtered) if filtered else None
Defensive patterns

Strategy: type-guard

Validate before calling

if not values:
    raise ValueError('no values to reduce')
m = abs_min(values)

Type guard

def is_non_empty(seq) -> bool:
    return len(seq) > 0

Prevention

When it happens

Trigger: Calling abs_min([]) - any empty sequence makes len(x) == 0 true and the guard fires before x[0] is accessed.

Common situations: Feeding in results of a filter/list comprehension that matched nothing, aggregating over an empty batch in a data pipeline, or processing empty input files line-by-line.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/f26e080b10550434. Report an issue: GitHub.