Python

# Calculate average in Python

arage.com@gmail.com

I will introduce a simple method to calculate averages using Python.

## Calculating Averages Using Python’s Standard Library

### Calculating Averages Using Python’s sum and len Functions

``````1mylist = [1, 2, 3, 4, 5]
2average = sum(mylist) / len(mylist)
3print(average)  # Outputs: 3.0``````

One of the most straightforward ways to calculate the average in Python is by using the built-in sum and len functions. The sum function returns the total sum of all the elements in a list, and the len function returns the length of the list. The average can be calculated as the sum of the elements divided by the number of elements. Here’s a simple example:

### Calculating Averages Using Python’s statistics Library’s mean Function

``````1import statistics
2
3mylist = [1, 2, 3, 4, 5]
4average = statistics.mean(mylist)
5print(average)  # Outputs: 3.0``````

Another way to calculate averages in Python is by using the mean function from the statistics library, which is a part of Python’s standard library. This function directly calculates the average of a list. Here’s how you can use it:

## Calculating Averages Using numpy

``````1import numpy
2
3myarray = numpy.array([1, 2, 3, 4, 5])
4average = numpy.mean(myarray)
5print(average)  # Outputs: 3.0``````

When working with larger datasets, especially multidimensional arrays, the mean function from the numpy library is a more efficient way to calculate averages. The use of numpy’s mean function is quite intuitive and straightforward:

## Advanced version to calculate the average

### Calculating the Average of a Specific Attribute in Objects

``````1class Person:
2    def __init__(self, age):
3        self.age = age
4
5people = [Person(10), Person(20), Person(30), Person(40), Person(50)]
6average_age = sum(map(lambda p: p.age, people)) / len(people)
7print(average_age)  # Output: 30.0``````

There may be times when you want to calculate the average of a specific attribute in objects. In such cases, you can use the map() function, a built-in function in Python, along with lambda functions to extract the attributes, and then compute the average.

### Calculating the Average of Elements in a Tuple

``````1my_tuple = (10, 20, 30, 40, 50)
2average = sum(my_tuple) / len(my_tuple)
3print(average)
``````

It can be implemented in the same way as for lists.