TheAlgorithms/Python · error · Exception

Invalid upper or lower bound!

Error message

Invalid upper or lower bound!

What it means

Raised by rec_linear_search in searches/linear_search.py when either the low or high index argument is outside the sequence bounds. The function searches inward from both ends simultaneously, so it demands 0 <= high < len(sequence) and 0 <= low < len(sequence); any out-of-range index raises a bare Exception (not ValueError, which is itself a code smell). The classic trigger is passing len(sequence) as high (off-by-one) instead of len(sequence) - 1.

Source

Thrown at searches/linear_search.py:58

    :param sequence: a collection with comparable items (as sorted items not required
        in Linear Search)
    :param low: Lower bound of the array
    :param high: Higher bound of the array
    :param target: The element to be found
    :return: Index of the key or -1 if key not found

    Examples:
    >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 0)
    0
    >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 700)
    4
    >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 30)
    1
    >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, -6)
    -1
    """
    if not (0 <= high < len(sequence) and 0 <= low < len(sequence)):
        raise Exception("Invalid upper or lower bound!")
    if high < low:
        return -1
    if sequence[low] == target:
        return low
    if sequence[high] == target:
        return high
    return rec_linear_search(sequence, low + 1, high - 1, target)


if __name__ == "__main__":
    user_input = input("Enter numbers separated by comma:\n").strip()
    sequence = [int(item.strip()) for item in user_input.split(",")]

    target = int(input("Enter a single number to be found in the list:\n").strip())
    result = linear_search(sequence, target)
    if result != -1:
        print(f"linear_search({sequence}, {target}) = {result}")
    else:

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass high = len(sequence) - 1 and low = 0 for a full search: rec_linear_search(seq, 0, len(seq) - 1, target).
  2. Validate bounds before the call: assert 0 <= low <= high < len(sequence).
  3. Catch it knowing it is a plain Exception (except Exception), or better, fix the caller so no exception occurs; consider contributing a patch to raise ValueError instead.

Example fix

# before
rec_linear_search(seq, 0, len(seq), target)  # high out of range

# after
rec_linear_search(seq, 0, len(seq) - 1, target)
Defensive patterns

Strategy: validation

Validate before calling

def safe_rec_linear_search(seq, target, low=0, high=None):
    if high is None:
        high = len(seq) - 1
    if not (0 <= low < len(seq) and 0 <= high < len(seq)):
        raise IndexError('low/high must be within [0, len(sequence))')
    return rec_linear_search(seq, low, high, target)

Try / catch

try:
    i = rec_linear_search(seq, low, high, target)
except Exception as e:  # note: bare Exception, not ValueError
    if 'Invalid upper or lower bound' in str(e):
        i = rec_linear_search(seq, 0, len(seq) - 1, target)
    else:
        raise

Prevention

When it happens

Trigger: rec_linear_search([0, 30, 500], 0, 0, 3) -> high == len -> raises; negative low like rec_linear_search(seq, x, -1, 4); calling with defaults omitted. The doctest-style API expects rec_linear_search(sequence, low, high, target), so swapping low/high also produces it when high lands out of range.

Common situations: Off-by-one errors from using len(seq) instead of len(seq) - 1; porting code from ranges where the end bound is exclusive; passing bounds from enumerate() or slice ends directly.

Related errors


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