MakeCodingSimple
July 7, 2023

How To Calculate Average From List in Python

Posted on July 7, 2023  (Last modified on July 11, 2023 )
2 minutes  • 399 words
Table of contents

How To Calculate Average from a List in Python

Calculating the average of a list is a common task in data analysis and programming. In this tutorial, we will guide you through the process of calculating the average from a list of numbers using Python with a few different methods

Here is a few method we can use to calculate the average number :

Method 1 : Using sum() and len() Function

One simple method to calculate the average from a list in Python is by using the built-in sum() and len() functions. The sum() function returns the sum of all the values in the list, and the len() function returns the number of elements in the list. By dividing the sum by the length, we can obtain the average.

num = [2, 4, 6, 8, 10]
average = sum(num) / len(num)
print(average)

Output:

6.0

Method 2: Using a for loop

Another way to calculate the average is by using a for loop. We can iterate over each element in the list, accumulate the sum of the list, and then divide it by the number of elements to obtain the average.

number = [2, 4, 6, 8, 10]
total = 0

# Iterate over each number in the list
for num in number:
    # Accumulate the sum of all numbers
    total += num

# Calculate the average by dividing the sum by the number of elements
average = total / len(number)

print(average)

Output:

6.0

Method 3: Using statistic module

Python’s statistics module provides functions to perform statistical operations, including calculating the average. We can use the mean() function from the statistics module to calculate the average from a list.

import statistics

num = [2, 4, 6, 8, 10]
average = statistics.mean(num)
print(average)

Output:

6

Conclusion:

Calculating the average from a list is a common task when working with data in Python. In this article, we explored different methods to calculate the average, including using the built-in functions, and statistical modules. By understanding these methods, you can choose the most suitable approach based on your specific requirements.


Share

 

Other Tutorial

 

Read Previous Read Next
How To Find The Smallest Number In A List In Python How To Convert A List Into A String In Python
Find Me in Social Media

Join our social media community and be part of the conversation! Follow us for inspiring content.