- Sum
- 15
- Count
- 5
Find Average of N Numbers in Python
What you’ll learn
- How average (arithmetic mean) works.
- How to compute average from user input and from a list.
- How to avoid divide-by-zero mistakes.
- How to explain time and space complexity in interviews.
Overview
Average is sum divided by number of items. In code: keep running sum, then divide by count.
What is average?
For numbers x1, x2, ..., xN, average is (x1 + x2 + ... + xN) / N, where N > 0.
This page focuses on arithmetic mean, not median or mode.
Quick examples
1,2,3,4,5Mean 3
10,15,20,25,30Mean 20
- Sum
- 100
- Count
- 5
N=0Invalid
- Reason
- Cannot divide by zero.
Live preview
Enter comma-separated numbers and view count, sum, and average.
Algorithm
Goal: find average of N numbers.
Read N
Make sure N is positive.
Initialize sum
Set sum = 0.
Loop N times
Add each input to sum.
Divide
Average = sum / N.
📜 Pseudocode
Pseudocode
function averageOfN(n):
if n <= 0:
return error
sum = 0
repeat n times:
read x
sum = sum + x
return sum / n1
Average from user input
python
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}")2
Average from a list
python
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}")❓ FAQ
Add all N numbers, then divide by N. Formula: average = sum / N.
Because division by zero is not allowed. If N is 0, average is undefined.
Use float when you want decimal output. Python handles both, but average is often fractional.
O(N), because we visit each number once to compute the sum.
O(1) extra if you only keep running sum and count. O(N) if you store all numbers in a list.
No. Average is sum/count, while median is the middle value after sorting.
Edge cases and pitfalls
N = 0
Invalid division
Always validate count before dividing.
Invalid input
Non-numeric values
Handle conversion errors in production code.
Precision
Floating point behavior
Decimal output may contain small rounding differences.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Running sum loop | O(N) | O(1) |
| Store list then compute | O(N) | O(N) |
Summary
- Formula: average = sum / count.
- Code: one loop for sum, one division at end.
- Safety: avoid divide-by-zero and bad inputs.
Did you know?
Average means sum divided by count. If the sum is 100 and count is 5, average is 20.
9 people found this page helpful
