TheAlgorithms/Python · error · ValueError

List is empty

Error message

List is empty

What it means

mean() raises ValueError('List is empty') when given an empty (or otherwise falsy) list, since sum/len is undefined for zero elements. This is a deliberate guard inside the arithmetic-mean helper.

Source

Thrown at maths/average_mean.py:21

def mean(nums: list) -> float:
    """
    Find mean of a list of numbers.
    Wiki: https://en.wikipedia.org/wiki/Mean

    >>> mean([3, 6, 9, 12, 15, 18, 21])
    12.0
    >>> mean([5, 10, 15, 20, 25, 30, 35])
    20.0
    >>> mean([1, 2, 3, 4, 5, 6, 7, 8])
    4.5
    >>> mean([])
    Traceback (most recent call last):
        ...
    ValueError: List is empty
    """
    if not nums:
        raise ValueError("List is empty")
    return sum(nums) / len(nums)


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard with `if not nums:` before calling and handle (skip, default, or surface a clearer domain error).
  2. Verify the data source actually produced values — an empty list often means an upstream fetch failed silently.
  3. Pass statistics.fmean or handle emptiness yourself if you want a different policy.

Example fix

# before
avg = mean(samples)

# after
avg = mean(samples) if samples else float('nan')
Defensive patterns

Strategy: validation

Validate before calling

if not nums:
    raise ValueError("cannot compute mean of empty list")
avg = mean(nums)

Type guard

def non_empty(nums: list[float] | None) -> bool:
    return bool(nums)

Try / catch

try:
    avg = mean(nums)
except ValueError:
    avg = float('nan')

Prevention

When it happens

Trigger: mean([]); mean(filtered_list) where the filter matched nothing; passing None also triggers it (None is falsy).

Common situations: Empty query results, empty CSV columns, sensors reporting no samples, or accidentally passing None instead of a list.

Related errors


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