Computing the average of a list is a foundational concept in programming, and is particularly important when performing statistical calculations or data analytics. In this tutorial, we shall go over how you can compute the average of a list in Python.
Python, a flexible, powerful, and widely used programming language, has several inherent methods for quickly computing averages.
Step 1: Understand Python Lists
To follow this tutorial, you need to have a basic understanding of what a Python list is. A list in Python is a built-in data structure that can be used to store a collection of items. These items can be of any type and a list can contain items of different types.
For example, you can have a list of integers as so: [1, 2, 3, 4, 5]
, or a list containing a mix of integers and strings: [1, 'two', 3, 'four', 5]
.
Step 2: Use the Built-in Python Function: sum()
Python comes with a built-in function sum()
that calculates the sum of all the elements in a list. This function directly takes a list as an input.
1 |
total = sum([1, 2, 3, 4, 5]) |
In the code above, we are calculating the sum of a list of integers and storing the result in the variable total
.
Step 3: Compute the Length of the List using len()
The next step is to calculate how many elements are there in the list. This is done using the built-in Python function len()
.
1 |
number_of_elements = len([1, 2, 3, 4, 5]) |
In this code, we are getting the number of elements in a list by using the len
function and storing the result in the variable number_of_elements
.
Step 4: Calculating the Average
Now that we’ve computed the sum of the elements in the list and how many elements are there, we can calculate the average. In statistics, the average (also known as the mean) of a set of numbers is the sum of the numbers divided by the total count.
1 |
average = total / number_of_elements |
Full Code
1 2 3 4 |
list_of_numbers = [1, 2, 3, 4, 5] total = sum(list_of_numbers) number_of_elements = len(list_of_numbers) average = total / number_of_elements |
Output
3.0
Conclusion
As you can see, computing the average of a list in Python is incredibly straightforward and noteworthy. Python consists of many potent features and built-in functions, and understanding how to use them can significantly improve your skills and efficiency as a programmer.