Python Program to Find Average of Numbers
To find the average of numbers in Python, sum the numbers using
sum() and divide by the count using len(), like average = sum(numbers) / len(numbers).Examples
Input[10, 20, 30]
Output20.0
Input[5, 15, 25, 35]
Output20.0
Input[100]
Output100.0
How to Think About It
To find the average, first add all the numbers together to get the total sum. Then count how many numbers there are. Finally, divide the total sum by the count to get the average value.
Algorithm
1
Get the list of numbers2
Calculate the sum of all numbers3
Count how many numbers are in the list4
Divide the sum by the count to get the average5
Return or print the averageCode
python
numbers = [10, 20, 30] average = sum(numbers) / len(numbers) print(average)
Output
20.0
Dry Run
Let's trace the example [10, 20, 30] through the code
1
Input list
numbers = [10, 20, 30]
2
Calculate sum
sum(numbers) = 10 + 20 + 30 = 60
3
Count numbers
len(numbers) = 3
4
Calculate average
average = 60 / 3 = 20.0
5
Print result
Output: 20.0
| Step | Sum | Count | Average |
|---|---|---|---|
| Initial | - | - | - |
| Calculate sum | 60 | - | - |
| Count numbers | 60 | 3 | - |
| Calculate average | 60 | 3 | 20.0 |
Why This Works
Step 1: Sum all numbers
Using sum() adds all numbers together to get the total.
Step 2: Count numbers
Using len() counts how many numbers are in the list.
Step 3: Divide sum by count
Dividing total sum by count gives the average value.
Alternative Approaches
Using a loop to calculate sum
python
numbers = [10, 20, 30] sum_numbers = 0 for num in numbers: sum_numbers += num average = sum_numbers / len(numbers) print(average)
This method shows the manual way to sum numbers but is longer than using built-in sum().
Using statistics.mean() function
python
import statistics numbers = [10, 20, 30] average = statistics.mean(numbers) print(average)
This uses Python's built-in statistics module for a clean and readable solution.
Complexity: O(n) time, O(1) space
Time Complexity
Calculating the sum requires visiting each number once, so it takes O(n) time where n is the number of elements.
Space Complexity
The program uses a fixed amount of extra space regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
Using built-in sum() is fastest and most readable; manual loops are slower and more verbose; statistics.mean() is clean but adds import overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Built-in sum() and len() | O(n) | O(1) | Simple and fast average calculation |
| Manual loop sum | O(n) | O(1) | Learning how summing works internally |
| statistics.mean() | O(n) | O(1) | Clean code with standard library support |
Use
sum() and len() together for a quick average calculation.Dividing by the wrong count or forgetting to convert to float can cause incorrect average results.