Formula
sum / N
Average = (x1 + x2 + … + xN) / N when N > 0.
The arithmetic mean of N numbers is their sum divided by N. This tutorial covers the formula, a live preview, algorithm steps, worked Python examples, edge cases, and complexity.
sum / N
Average = (x1 + x2 + … + xN) / N when N > 0.
O(1) space
Add each value into a total, then divide once at the end.
Read N values
Ask for N, then read N numbers from the user and accumulate.
sum / len
When values are already in a list, use sum(values) / len(values).
Try any set
Paste comma-separated numbers and see count, sum, and mean instantly.
Complexity
One pass over the values; extra space is O(1) or O(N) depending on storage.
The average (arithmetic mean) of N numbers is their total sum divided by how many numbers you have. In code you usually keep a running sum, then divide by N once at the end.
This page focuses on arithmetic mean — not median or mode. You will see an input-loop version, a list-based helper, and a short statistics.mean variant.
It trains loops, accumulation, division safety, and float output — fundamentals every beginner interview expects.
One pass to add, one division for the mean.
Average is undefined when the count is zero.
Means are often fractional — prefer float division.
Median needs sorting; average only needs sum and count.
In short: add the N numbers, divide by N (when N > 0), and that quotient is the average.
Given N positive count and N numeric values, compute their arithmetic mean.
# Example: 1, 2, 3, 4, 5
# Sum = 15, N = 5
# Average = 15 / 5 = 3.0 | Item | Type | Description |
|---|---|---|
N / values | int / floats | Count of numbers and the numbers themselves (N must be > 0). |
| Return / print | float / text | Arithmetic mean sum / N. |
function averageOfN(n):
if n <= 0:
return error
sum = 0
repeat n times:
read x
sum = sum + x
return sum / n | Method | Idea | Extra space |
|---|---|---|
| Running sum | Accumulate while reading; divide at end | O(1) |
| List then mean | Store all values; sum / len | O(N) |
| Goal | Pattern |
|---|---|
| Formula | average = sum / N |
| Running total | total += value |
| List mean | sum(values) / len(values) |
| Empty guard | if n <= 0 or if not values |
| Stdlib helper | statistics.mean(values) |
| Pretty print | f"{avg:.6f}" |
Related stats words — different algorithms.
sum / NThis tutorial — one pass sum, then divide
middle after sortNeeds ordered data; not the same as average
most frequentCounts occurrences; different problem entirely
name meanSay “arithmetic mean” so interviewers know you mean sum/N
Reach for average drills when sum loops and division safety matter.
Quick check of loops, accumulation, and empty-input handling.
Classic first program after learning for and input().
Scores, temperatures, and sensor readings often need a mean.
Running-sum style works when you cannot store the whole list.
If outliers matter, interviewers may ask for median instead — clarify first.
Key benefit: one tiny problem that covers loops, floats, divide-by-zero, and O(N) complexity talk.
Enter comma-separated numbers and view count, sum, and average.
Three complete Python programs — input loop, list helper, and statistics.mean. Click View Output to reveal sample console results.
Read N values from the console and accumulate.
Validate N, loop N times, keep a running total, then divide.
def average_of_n_numbers(n: int) -> float:
if n <= 0:
return 0.0
total = 0.0
print(f"Enter {n} numbers:")
for _ in range(n):
value = float(input())
total += value
return total / n
n = 5
result = average_of_n_numbers(n)
print(f"The average of the entered numbers is: {result:.6f}") Guard non-positive N, accumulate floats into total, then return total / n. Using float keeps fractional means exact for common school examples.
When the values already live in a list.
Use built-in sum and len — short and interview-friendly.
def average_from_list(values: list[float]) -> float:
if not values:
return 0.0
return sum(values) / len(values)
data = [10, 15, 20, 25, 30]
avg = average_from_list(data)
print(f"Average = {avg:.6f}") Empty lists return a documented sentinel (0.0 here). Otherwise sum(values) / len(values) is exactly the arithmetic mean.
Same math via the statistics module.
statistics.meanPrefer this in application code when a non-empty sequence is guaranteed.
from statistics import mean
data = [1, 2, 3, 4, 5]
print(mean(data)) mean computes the arithmetic mean of a non-empty sequence. An empty sequence raises StatisticsError — handle that if emptiness is possible.
If the count is zero or negative, stop — division would be invalid.
Add each number into a running total (or call sum on a list).
Compute total / N (or sum / len) as a float mean.
Print or return the quotient — that is the arithmetic mean.
1, 2, 3, 4, 5Trace a running-sum loop for five values. Start with total = 0.0 and N = 5.
| Step | Value | total after add |
|---|---|---|
| 1 | 1 | 1.0 |
| 2 | 2 | 3.0 |
| 3 | 3 | 6.0 |
| 4 | 4 | 10.0 |
| 5 | 5 | 15.0 |
Final mean: 15.0 / 5 = 3.0.
Where average-of-N checks show up beyond the interview prompt.
Tests loops, floats, and empty-input guards.
Example: write average_of_n(n).
Class marks or game scores often need a mean.
Example: average of five test scores.
Smooth noisy measurements with a simple mean.
Example: average of last N samples.
Makes running totals feel concrete before harder stats.
Example: chalkboard sum of 1…5.
O(1) extra space when you cannot store every value.
Example: online mean while reading a file.
Argue O(N) time and O(1) vs O(N) space cleanly.
Example: loop vs list storage.
Pro Tip: keep a pure average_from_list helper and wrap input separately — easier to test.
Why this pattern works well in interviews and classwork.
Sum then divide — almost no translation gap from math to code.
A running total never needs to store the full list.
sum, len, and statistics.mean keep production code short.
Empty / N=0 is an obvious safety point interviewers love to hear.
Pro Tip: say “arithmetic mean = sum / count” before coding — it frames the whole solution.
Small habits that keep average code interview-ready.
Check N > 0 or non-empty lists before dividing.
Start with total = 0.0 so fractional means stay natural.
Parse values first, then call a pure average helper.
Assert 1…5 → 3.0 and 10…30 step 5 → 20.0.
Ask whether to return 0, raise, or None when N is zero.
Pro Tip: dry-run 1…5 on paper once — it catches off-by-one loop bounds faster than guessing.
Mistakes that commonly break average solutions.
Empty lists or N = 0 crash or return nonsense.
→ Validate count before the division.
Sorting and picking the middle value is a different algorithm.
→ Confirm the prompt asks for arithmetic mean.
In some languages sum / N truncates; Python 3 / is float, but be explicit.
→ Use floats or format the printed mean clearly.
Non-numeric strings break float(input()) or parsers.
→ Catch conversion errors in production code.
Reading N-1 or N+1 values skews the mean.
→ Loop exactly range(n) and trust that count.
Check these inputs before calling the solution done.
Always validate count before dividing.
Return a sentinel, raise, or error — do not divide.
Average of a single number is itself.
Handle conversion errors in production code.
Means can be negative; do not reject signed numbers.
Printed decimals may show tiny floating-point noise.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
statistics.meanQuick Takeaway: add the numbers, divide by how many there are — and never divide by zero.
| Program | Time | Extra space |
|---|---|---|
| Running sum loop | O(N) | O(1) |
| Store list then compute | O(N) | O(N) |
statistics.mean | O(N) | depends on input storage |
Finding the average of N numbers is a clean accumulation exercise: validate the count, sum the values, divide once. Master the input loop and the list helper, then mention statistics.mean for application code.
Practice the three examples above, then continue to biggest-of-three-numbers for another classic comparison warm-up.
Never divide by zero, never confuse mean with median, and always state O(N) when asked about complexity.
Compute the mean the interview-friendly way.
sum / N
DefinitionRunning total
CodeN must be > 0
Guardsum / len
CodeO(N) time
AnalysisAverage means sum divided by count. If the sum is 100 and count is 5, average is 20.
Learn how to find the largest value among three numbers in Python.
9 people found this page helpful