TheAlgorithms/Python · error · ValueError

input list must not be empty

Error message

input list must not be empty

What it means

Raised by find_unique_number when the input list is empty. The function finds the element appearing once by XOR-folding the whole list; an empty list has no unique element, so it refuses rather than returning the XOR identity 0.

Source

Thrown at bit_manipulation/find_unique_number.py:24

    >>> find_unique_number([1, 1, 2, 2, 3])
    3
    >>> find_unique_number([4, 5, 4, 6, 6])
    5
    >>> find_unique_number([7])
    7
    >>> find_unique_number([10, 20, 10])
    20
    >>> find_unique_number([])
    Traceback (most recent call last):
        ...
    ValueError: input list must not be empty
    >>> find_unique_number([1, 'a', 1])
    Traceback (most recent call last):
        ...
    TypeError: all elements must be integers
    """
    if not arr:
        raise ValueError("input list must not be empty")
    if not all(isinstance(x, int) for x in arr):
        raise TypeError("all elements must be integers")

    result = 0
    for num in arr:
        result ^= num
    return result


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check truthiness at the call site: skip or return None when not arr.
  2. Fix upstream filtering so the 'every element appears twice except one' precondition is actually met before calling.
  3. If empty means 'no answer', return a sentinel explicitly instead of relying on the exception.

Example fix

# before
unique = find_unique_number(group)  # group can be []

# after
unique = find_unique_number(group) if group else None
Defensive patterns

Strategy: validation

Validate before calling

if not arr:
    return None  # or skip, per your domain
return find_unique_number(arr)

Try / catch

try:
    unique = find_unique_number(items)
except ValueError:
    unique = None  # empty batch has no unique element

Prevention

When it happens

Trigger: Calling find_unique_number([]). The check runs before the element-type check, so an empty list of anything raises this, not the TypeError.

Common situations: Processing batches/chunks where a filter or group-by produced zero elements; forgetting to handle empty input before reduction-style helpers.

Related errors


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