Just as strings are defined as characters between quotes, we can define lists by specifying values between square brackets. A simple example is [1,2,3,4,5].
Find the average of a list in python In simple words, a python list is a changeable data structure.
Furthermore, this sequence is ordered and all elements inside a list are called items.
Contents
Find the average of a list in python
Defining a list in python is simple since all you have to do is define your values within square brackets. For example:
a=[5,6,33.4];
Find the average of a list in python. In the above example, we created a list with some values and stored it in the variable a. After assigning values, we can perform multiple operations on the list such as printing the items, adding, finding out the average, and so on. This article will show you how you can find out the average of all items present in a list. So without further ado, let’s get into it.
a=[2,3,44,23,45,66] sum=0 for i in a: sum=sum+i average=sum/len(a) print('The average of the list is '+<em>str</em>(average))
Expalination
In the first step, we simply defined a list by initializing items of our choice. These items can, of course, be changed by a different programmer.
Furthermore, we can allow the user to define a list of his choice and then calculate its average. But for the sake of simplicity, we will use a list that we define in our source code.
Next, we initialized the value of the sum to be zero so that we can add the value of the list items into it. To achieve this, we defined a for-loop that iterates within the list a. Now, in the for-loop, we told the program to add the value of the item to sum, which was initially zero.
sum
- So after the first iteration, the value of the sum would change from zero to 2.
- The next iteration, it would change from 2 to 5 since 5 will be added to the previous value of sum(which was 2).
- For loop would repeat this process for every single item present in the list. By the end of the loop, the sum would be equal to 183.
- In the next step, we calculate the average by dividing the sum by the number of items present in the list.
- In this example, the average will be equal to 30.5.
This is so because the sum we calculated using the for-loop was then divided with the length of the list or in other words, the number of items present in the list which is 6 in our case.
Finally, the output will be printed like:
The average of the list is 30.5.
Some reasons to find the average of a list in Python are:
- To get a representative value for a list of numbers.
- To calculate an average score or grade.
- Find the mean or median of a list of data.
Conclusion
There are other ways in which you can calculate the average of the items present in the list but this method is probably the most simple.
Read More: 5 Ways to Initialize a Python Array