TheAlgorithms/Python · error · ValueError
List is empty
Error message
List is empty
What it means
average_absolute_deviation() computes the mean absolute deviation of a list of numbers; it raises ValueError('List is empty') when nums is falsy because the mean (and hence the deviation) is undefined for zero elements.
Source
Thrown at maths/average_absolute_deviation.py:20
"""
Return the average absolute deviation of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Average_absolute_deviation
>>> average_absolute_deviation([0])
0.0
>>> average_absolute_deviation([4, 1, 3, 2])
1.0
>>> average_absolute_deviation([2, 70, 6, 50, 20, 8, 4, 0])
20.0
>>> average_absolute_deviation([-20, 0, 30, 15])
16.25
>>> average_absolute_deviation([])
Traceback (most recent call last):
...
ValueError: List is empty
"""
if not nums: # Makes sure that the list is not empty
raise ValueError("List is empty")
average = sum(nums) / len(nums) # Calculate the average
return sum(abs(x - average) for x in nums) / len(nums)
if __name__ == "__main__":
import doctest
doctest.testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Check the list is non-empty before calling; skip or default when it is empty.
- Log which input produced the empty list to find the data pipeline issue.
- If aggregating many groups, wrap per-group so one empty group doesn't abort the run.
Example fix
# before mad = average_absolute_deviation(data) # after mad = average_absolute_deviation(data) if data else 0.0
Defensive patterns
Strategy: validation
Validate before calling
if not nums:
raise ValueError("cannot compute average absolute deviation of empty data") Type guard
def has_elements(nums: list[float]) -> bool:
return isinstance(nums, list) and len(nums) > 0 Try / catch
try:
mad = average_absolute_deviation(nums)
except ValueError as e:
if str(e) == "List is empty":
mad = 0.0 # or skip record
else:
raise Prevention
- Check truthiness of collections before statistical calls
- Log the source of empty lists to catch upstream fetch failures
When it happens
Trigger: average_absolute_deviation([]), or passing a list populated by a filter/slice that ended up empty, e.g. average_absolute_deviation([x for x in data if x > 100]).
Common situations: Empty datasets after filtering; API responses returning empty arrays; batch jobs where one input group has no rows.
Related errors
- List is empty
- successes must be lower or equal to trials
- the function is defined for non-negative integers
- prob has to be in range of 1 - 0
- Not a Number
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/f60da53847c60f0a.
Report an issue: GitHub.