TheAlgorithms/Python · error · TypeError

all elements must be integers

Error message

all elements must be integers

What it means

Raised by find_unique_number when any element of the list is not an int. The XOR fold requires homogeneous integers; mixing types would raise a confusing operand TypeError deep in the loop, so the function validates all elements up front. Note: bools pass because isinstance(True, int) is True.

Source

Thrown at bit_manipulation/find_unique_number.py:26

    >>> 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. Coerce elements: find_unique_number([int(x) for x in arr]) when all items are numeric.
  2. Filter or fix the data source so the list contains only integers.
  3. Add an explicit element-type check where the data enters your program, not where the algorithm runs.

Example fix

# before
find_unique_number([1, 'a', 1])  # TypeError

# after
find_unique_number([int(x) for x in ['1', '1', '20']])  # 20
Defensive patterns

Strategy: type-guard

Validate before calling

if not all(isinstance(x, int) and not isinstance(x, bool) for x in arr):
    raise TypeError("all elements must be integers")

Type guard

def all_ints(arr: list) -> bool:
    return all(isinstance(x, int) for x in arr)

Try / catch

try:
    unique = find_unique_number(arr)
except TypeError:
    unique = find_unique_number([int(x) for x in arr])

Prevention

When it happens

Trigger: Calling find_unique_number([1, 'a', 1]) or any list containing floats/strings/None among the ints.

Common situations: Lists built from mixed parsing (some fields ints, some strings), JSON arrays with heterogeneous numbers, or flags/None leaking into numeric data.

Related errors


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