TheAlgorithms/Python · error · ValueError

Input sequence should not be empty

Error message

Input sequence should not be empty

What it means

Raised by max_subsequence_sum when nums is None or an empty sequence. The algorithm seeds its running answer with nums[0], so at least one number is required; both a missing argument (default None) and an empty list are rejected.

Source

Thrown at other/maximum_subsequence.py:24

    Raises:
      ValueError: when nums is empty.

    >>> max_subsequence_sum([1,2,3,4,-2])
    10
    >>> max_subsequence_sum([-2, -3, -1, -4, -6])
    -1
    >>> max_subsequence_sum([])
    Traceback (most recent call last):
        . . .
    ValueError: Input sequence should not be empty
    >>> max_subsequence_sum()
    Traceback (most recent call last):
        . . .
    ValueError: Input sequence should not be empty
    """
    if nums is None or not nums:
        raise ValueError("Input sequence should not be empty")

    ans = nums[0]
    for i in range(1, len(nums)):
        num = nums[i]
        ans = max(ans, ans + num, num)

    return ans


if __name__ == "__main__":
    import doctest

    doctest.testmod()

    # Try on a sample input from the user
    n = int(input("Enter number of elements : ").strip())
    array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
    print(max_subsequence_sum(array))

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard the call: if nums: total = max_subsequence_sum(nums) else: handle the empty case
  2. Pass a non-empty list; even all-negative inputs are fine (e.g. [-2,-3,-1] returns -1)
  3. If the empty case is valid in your domain, decide its semantics (0 or None) before calling

Example fix

# before
best = max_subsequence_sum(window)  # ValueError when window == []

# after
best = max_subsequence_sum(window) if window else 0
Defensive patterns

Strategy: validation

Validate before calling

def has_elements(nums) -> bool:
    return nums is not None and len(nums) > 0

Try / catch

try:
    best = max_subsequence_sum(nums)
except ValueError as e:
    if 'should not be empty' in str(e):
        best = 0  # define your own empty-sequence semantics
    else:
        raise

Prevention

When it happens

Trigger: Calling max_subsequence_sum([]), max_subsequence_sum(None), or max_subsequence_sum() with no argument.

Common situations: Streaming or filtered data where an empty batch reaches the sum function, or calling with a default-None parameter that was never populated.

Related errors


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