Calculate the average of list of numbers in python

problem

You are learning programming using Python and wish to calculate the average (median) value of a list of numbers. In this post we will see how to calculate it.

SOLUTION

In order to calculate the average of numbers we first need to calculate the total (sum) and then divide that by how many numbers exist in the list.

The quickest way is by using two built-in functions, the sum() to calculate the total and the len() that counts elements in a list.

For example:

average.py
				
					numbers = [3,4,5,1,8,9,100,7]
total = sum(numbers)
count = len(numbers)
average = total / count
print(average)
				
			
running
				
					python3 average.py
				
			

or copy – paste the code in the shell

output
average of list in Python

Another one way is by calculating the sum using a for loop.

For example:

average2.py
				
					numbers = [3,4,5,1,8,9,100,7]
total  = 0
count = 0
for num in numbers:
	total = total + num
	count = count + 1
average = total / count
print(average)

				
			
running
				
					python3 average2.py
				
			
output

conclusion

In this post we saw two ways for calculating the average of a list of numbers in Python.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x