How do I find the average of a list of numbers in Python?
Average means adding up all the items to the list and then dividing by the number of numbers in the list.
- def average(num):
- sum = 0
- for i in num:
- sum = sum + i
- avg = sum / len(num)
- return avg
- print("The average is", average([19,2,53,32,15]))
The sum() and len() built-in functions are used to find intermediate levels in Python
- list = [1,2,3,4,5]
- avg = sum(list)/len(list)
- print("The average is ", round(avg,2))
Also, you can find out the average of a list using the mean method from the NumPy library.
- from numpy import mean
- list = [5, 3, 4, 35, 12, 6, 42]
- avg = mean(list)
- print("The average is ", round(avg,2))
Comments
Post a Comment