TheAlgorithms/Python · error · ValueError

Invalid value of 'position'

Error message

Invalid value of 'position'

What it means

Raised by kth_largest_element() in data_structures/arrays/kth_largest_element.py when position is an int but outside 1..len(arr) inclusive. position=1 means the largest element and position=len(arr) the smallest; anything else (0, negative, or greater than the length) is rejected.

Source

Thrown at data_structures/arrays/kth_largest_element.py:99

        >>> kth_largest_element([-2, -5, -4, -1], 1)
        -1
        >>> kth_largest_element([], 1)
        -1
        >>> kth_largest_element([3.1, 1.2, 5.6, 4.7, 7.9, 5, 0], 1.5)
        Traceback (most recent call last):
        ...
        ValueError: The position should be an integer
        >>> kth_largest_element((4, 6, 1, 2), 4)
        Traceback (most recent call last):
        ...
        TypeError: 'tuple' object does not support item assignment
    """
    if not arr:
        return -1
    if not isinstance(position, int):
        raise ValueError("The position should be an integer")
    if not 1 <= position <= len(arr):
        raise ValueError("Invalid value of 'position'")
    low, high = 0, len(arr) - 1
    while low <= high:
        if low > len(arr) - 1 or high < 0:
            return -1
        pivot_index = partition(arr, low, high)
        if pivot_index == position - 1:
            return arr[pivot_index]
        elif pivot_index > position - 1:
            high = pivot_index - 1
        else:
            low = pivot_index + 1
    return -1


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Clamp or reject k at the call site: if not 1 <= k <= len(arr): handle.
  2. Remember this API is 1-based: k=1 is the largest, k=len(arr) the smallest.
  3. For top-k features, check k against the current data size before every call (data may have shrunk).

Example fix

# before
best = kth_largest_element(scores, 0)  # expecting max

# after
best = kth_largest_element(scores, 1)  # max, 1-based
Defensive patterns

Strategy: validation

Validate before calling

if not 1 <= k <= len(arr):
    raise ValueError(f'k must be in 1..{len(arr)}')
result = kth_largest_element(arr, k)

Prevention

When it happens

Trigger: Calling kth_largest_element([3,1,5,4,7,5,0], 0), kth_largest_element([3,1,5], 4), or any position > len(arr).

Common situations: Confusing 0-based and 1-based semantics (asking for 'position 0' expecting the max), k larger than the dataset size in top-k queries, or k computed as len(arr) + 1 by an off-by-one loop.

Related errors


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