To calculate the average of a list of numbers in Python, the easiest way is to divide the sum of the list by the length of the list with the sum() and len() functions.

l = [1,2,3,4,5,6,7]

print(sum(l)/len(l))

#Output:
4

You can also use the mean() function from the statistics module to get the average of a list.

from statistics import mean

l = [1,2,3,4,5,6,7]

print(mean(l))

#Output:
4

You can also use a for loop to sum the numbers of a list and then divide by the length of the list to get the mean of a list in Python.

l = [1,2,3,4,5,6,7]

def mean(lst):
    s = 0
    for num in lst:
        s = s + num
    return s / len(lst)

print(mean(l))

#Output:
4

When working with collections of data in Python, the ability to summarize the data easily is valuable.

One such case is if you want to get the average of a list of numbers.

To get the average of a list, you get the sum of the list and divide by the number of items in the list.

To calculate the average of a list of numbers in Python, the easiest way is with the sum() and len() functions.

sum() returns the sum of a list of numbers, and len() returns the length of the list.

Below shows you how to get the average of a list of numbers in Python with sum() and len().

l = [1,2,3,4,5,6,7]

print(sum(l)/len(l))

#Output:
4

Using statistics Module mean Function to Get Average of List in Python

A useful module in Python is the statistics module. The statistics module has many great functions for performing different calculations.

One such calculation is finding the mean of a collection of data.

You can use the statistics module mean() function to get the average of a list in Python.

Below shows you how to use mean() to get the average of a list in Python.

from statistics import mean

l = [1,2,3,4,5,6,7]

print(mean(l))

#Output:
4

Using For Loop to Get Average of List in Python

Another way you can get the mean of numbers of a list is with a for loop to get the sum and then use len() to get the length of the list.

To add the numbers of a list up, initialize a variable which will keep the running sum and then add each element to the running sum.

Then divide by the length of the list.

Below shows you how to get the average of a list of numbers in Python with a for loop.

l = [1,2,3,4,5,6,7]

def mean(lst):
    s = 0
    for num in lst:
        s = s + num
    return s / len(lst)

print(mean(l))

#Output:
4

Hopefully this article has been useful for you to learn how to get the average of a list in Python.

Categorized in:

Python,

Last Update: March 22, 2024