Python Program to Find Average of List
To find the average of a list in Python, use
average = sum(your_list) / len(your_list) where sum() adds all numbers and len() counts them.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 in the list to get the total sum. Then count how many numbers are in the list. Finally, divide the total sum by the count to get the average value.
Algorithm
1
Get the list of numbers.2
Calculate the sum of all numbers in the list.3
Count how many numbers are in the list.4
Divide the sum by the count to get the average.5
Return or print the average.Code
python
numbers = [10, 20, 30] average = sum(numbers) / len(numbers) print(average)
Output
20.0
Dry Run
Let's trace the list [10, 20, 30] through the code
1
List input
numbers = [10, 20, 30]
2
Calculate sum
sum(numbers) = 10 + 20 + 30 = 60
3
Count elements
len(numbers) = 3
4
Calculate average
average = 60 / 3 = 20.0
5
Print result
print(average) outputs 20.0
| Step | Sum | Count | Average |
|---|---|---|---|
| Initial | - | - | - |
| Sum calculation | 60 | - | - |
| Count calculation | - | 3 | - |
| Average calculation | - | - | 20.0 |
Why This Works
Step 1: Sum all numbers
The sum() function adds all numbers in the list to get the total.
Step 2: Count numbers
The len() function counts how many numbers are in the list.
Step 3: Divide sum by count
Dividing the total sum by the count gives the average value.
Alternative Approaches
Using a loop to calculate sum
python
numbers = [10, 20, 30] total = 0 for num in numbers: total += num average = total / len(numbers) print(average)
This method is more manual but helps understand how sum works internally.
Using statistics.mean() function
python
import statistics numbers = [10, 20, 30] average = statistics.mean(numbers) print(average)
This uses a built-in function designed for averages, making code cleaner.
Complexity: O(n) time, O(1) space
Time Complexity
Calculating the sum requires visiting each element once, so it takes O(n) time where n is the number of elements.
Space Complexity
The calculation uses a fixed amount of extra space regardless of input size, so it is O(1).
Which Approach is Fastest?
Using built-in sum() is usually fastest and simplest; manual loops are slower but educational; statistics.mean() is clean and reliable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Built-in sum()/len() | O(n) | O(1) | Simple and fast for all lists |
| Manual loop sum | O(n) | O(1) | Learning how summing works |
| statistics.mean() | O(n) | O(1) | Clean code and extra stats features |
Always check the list is not empty before dividing to avoid errors.
Dividing by zero when the list is empty causes a runtime error.