TheAlgorithms/Python · error · ValueError

Input series is not valid, valid series - [2, 4, 6]

Error message

Input series is not valid, valid series - [2, 4, 6]

What it means

Raised by harmonic_mean() in maths/series/harmonic.py when the argument is not a list instance. The function sums reciprocals 1/val over the elements, requiring an indexable Python list of numbers. The '[2, 4, 6]' in the message is just a sample of a valid input, which can mislead developers into thinking their values are wrong when actually the type is wrong.

Source

Thrown at maths/series/harmonic.py:80

    >>> harmonic_mean([1, 4, 4])
    2.0
    >>> harmonic_mean([3, 6, 9, 12])
    5.759999999999999
    >>> harmonic_mean(4)
    Traceback (most recent call last):
        ...
    ValueError: Input series is not valid, valid series - [2, 4, 6]
    >>> harmonic_mean([1, 2, 3])
    1.6363636363636365
    >>> harmonic_mean([])
    Traceback (most recent call last):
        ...
    ValueError: Input list must be a non empty list

    """
    if not isinstance(series, list):
        raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
    if len(series) == 0:
        raise ValueError("Input list must be a non empty list")
    answer = 0
    for val in series:
        answer += 1 / val
    return len(series) / answer


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Coerce to list: harmonic_mean(list(values))
  2. Convert numpy arrays: harmonic_mean(arr.tolist())
  3. Parse string input into a list of floats before calling

Example fix

# before
harmonic_mean((1, 2, 3))  # tuple -> ValueError

# after
from statistics import harmonic_mean as st_hm  # or:
print(harmonic_mean([1, 2, 3]))  # -> 1.6363...
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(series, list):
    series = [float(x) for x in series]
print(harmonic_mean(series))

Type guard

def is_float_list(value: object) -> bool:
    return isinstance(value, list) and all(
        isinstance(x, (int, float)) and x != 0 for x in value
    )

Prevention

When it happens

Trigger: Calling harmonic_mean(3), harmonic_mean('123'), harmonic_mean((1,2,3)), or passing any non-list object. This isinstance check runs before the emptiness check, so non-list empties (like empty tuple) fail here too.

Common situations: Passing tuples or other iterables from libraries with different conventions; forgetting to .split() or json.loads a raw input string; numpy arrays not converted with .tolist().

Related errors


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