TheAlgorithms/Python · error · ValueError

find_max_iterative() arg is an empty sequence

Error message

find_max_iterative() arg is an empty sequence

What it means

Raised by find_max_iterative() in maths/find_max.py when nums is an empty sequence. A maximum of zero elements does not exist, and the algorithm seeds max_num = nums[0], so it rejects empty input up front with ValueError (mirroring built-in max() behavior).

Source

Thrown at maths/find_max.py:20


def find_max_iterative(nums: list[int | float]) -> int | float:
    """
    >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):
    ...     find_max_iterative(nums) == max(nums)
    True
    True
    True
    True
    >>> find_max_iterative([2, 4, 9, 7, 19, 94, 5])
    94
    >>> find_max_iterative([])
    Traceback (most recent call last):
        ...
    ValueError: find_max_iterative() arg is an empty sequence
    """
    if len(nums) == 0:
        raise ValueError("find_max_iterative() arg is an empty sequence")
    max_num = nums[0]
    for x in nums:
        if x > max_num:  # noqa: PLR1730
            max_num = x
    return max_num


# Divide and Conquer algorithm
def find_max_recursive(nums: list[int | float], left: int, right: int) -> int | float:
    """
    find max value in list
    :param nums: contains elements
    :param left: index of first element
    :param right: index of last element
    :return: max in nums

    >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):
    ...     find_max_recursive(nums, 0, len(nums) - 1) == max(nums)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check for empty input first and decide domain semantics (default value, skip, or error).
  2. Use `find_max_iterative(nums) if nums else default` or Python's `max(nums, default=...)` pattern if you switched to built-ins.
  3. Validate collection size at the data-loading boundary so downstream max calls are safe.

Example fix

# before
peak = find_max_iterative(samples)  # raises when samples == []

# after
peak = find_max_iterative(samples) if samples else float('-inf')
Defensive patterns

Strategy: validation

Validate before calling

if not nums:
    raise ValueError('cannot compute max of empty input')
peak = find_max_iterative(nums)

Type guard

def is_nonempty_seq(nums: object) -> bool:
    return hasattr(nums, '__len__') and len(nums) > 0

Prevention

When it happens

Trigger: Calling find_max_iterative([]) (per its doctest). The `if len(nums) == 0` guard raises before nums[0] would raise IndexError.

Common situations: Finding the max of filtered/aggregated data that can legitimately be empty (no matching rows, empty batches), processing streams where the first chunk is empty, or assuming input is non-empty from a file or API response.

Related errors


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