Compute the mean of a Python list safely, returning 0.0 for an empty list instead of crashing with ZeroDivisionError. Simple but often fumbled — run it.
The problem
Return the average of nums as a float. Return 0.0 for an empty list.
Examples
Example 1
Input
average([1, 2, 3, 4])
Expected output
2.5
Example 2
Input
average([10])
Expected output
10.0
+ 2 hidden tests on Submit.
Edge cases to ask about
- Empty list
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| sum / len | O(n) | O(1) | Guard against dividing by zero. |
Walkthrough of the optimal approach (try it yourself first)
sum(nums) / len(nums) — with a guard, because an empty list would raise ZeroDivisionError. In Python 3, / is true division, so the result is a float. statistics.mean also exists.
Complexity: O(n) time, O(1) space. sum() makes one pass; len() is O(1).
Reveal the reference solution
def average(nums): if not nums: return 0.0 return sum(nums) / len(nums)
Follow-ups interviewers ask
- Running average of a stream without storing it.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Average of a List of Numbers in Python?
The optimal solution runs in O(n) time and O(1) auxiliary space. sum() makes one pass; len() is O(1).
What follow-up questions do interviewers ask about Average of a List of Numbers?
Running average of a stream without storing it.
