{"record":{"id":"048a2e947d3e5fad","repo":"TheAlgorithms/Python","slug":"list-is-empty-048a2e","errorCode":null,"errorMessage":"List is empty","messagePattern":"List is empty","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/average_mean.py","lineNumber":21,"sourceCode":"\ndef mean(nums: list) -> float:\n    \"\"\"\n    Find mean of a list of numbers.\n    Wiki: https://en.wikipedia.org/wiki/Mean\n\n    >>> mean([3, 6, 9, 12, 15, 18, 21])\n    12.0\n    >>> mean([5, 10, 15, 20, 25, 30, 35])\n    20.0\n    >>> mean([1, 2, 3, 4, 5, 6, 7, 8])\n    4.5\n    >>> mean([])\n    Traceback (most recent call last):\n        ...\n    ValueError: List is empty\n    \"\"\"\n    if not nums:\n        raise ValueError(\"List is empty\")\n    return sum(nums) / len(nums)\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n","sourceCodeStart":3,"sourceCodeEnd":29,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/average_mean.py#L3-L29","documentation":"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.","triggerScenarios":"mean([]); mean(filtered_list) where the filter matched nothing; passing None also triggers it (None is falsy).","commonSituations":"Empty query results, empty CSV columns, sensors reporting no samples, or accidentally passing None instead of a list.","solutions":["Guard with `if not nums:` before calling and handle (skip, default, or surface a clearer domain error).","Verify the data source actually produced values — an empty list often means an upstream fetch failed silently.","Pass statistics.fmean or handle emptiness yourself if you want a different policy."],"exampleFix":"# before\navg = mean(samples)\n\n# after\navg = mean(samples) if samples else float('nan')","handlingStrategy":"validation","validationCode":"if not nums:\n    raise ValueError(\"cannot compute mean of empty list\")\navg = mean(nums)","typeGuard":"def non_empty(nums: list[float] | None) -> bool:\n    return bool(nums)","tryCatchPattern":"try:\n    avg = mean(nums)\nexcept ValueError:\n    avg = float('nan')","preventionTips":["Guard `if not nums` before every mean/average call","Distinguish None from [] in your data model to give better upstream errors"],"tags":["math","statistics","empty-collection"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}