Find Average of List Using the Statistics Library Next, let’s see how we can calculate the average of a Python list using the statistics library. We then create a new variable and use the mean function, passing in the list as the argument.We imported mean from numpy, which is a function used to calculate the mean.Let’s see how we can work with numpy to calculate the average of a list: # Using numpy to calculate the average of a list Numpy comes built-in with a number of mathematical functions that make it easy to calculate various statistics, such as an average. If you’re working with numbers, chances are you’re using numpy in your script, meaning you can easily use some of its built-in functions. Calculate Average of Python List using Numpy In the example above, you turned the simple calculation of dividing the sum of a list by its length into a function to make it re-usable throughout your scripts. Return sum(list_to_use) / len(list_to_use) let’s see how to do this: # Creating a function to calculate an average of a list That way you can pass in any list and return its average. If you find yourself doing this frequently in a script, you can turn this into a function. Let’s see how we can accomplish this: # Calculating the average of a list using sum() and len() In order to do this, you first calculate the sum of a list and then divide it by the length of that list. ![]() ![]() Python doesn’t have a built-in function to calculate an average of a list, but you can use the sum() and len() functions to calculate an average of a list. Calculate Average of Python List using sum and len This is a fairly labour-intensive way of calculating an average in Python, but it shows how it can be done. ![]() Let’s see how this can be done: # Calculating the average of list using a for loop One naive way that you can calculate the average in Python is using a for loop. You simply add up an array of numbers and divide it by the length of that array. How can you calculate an average in Python?Ĭalculating the average of different values in Python is very straightforward. Find Average of List Using the Statistics Library.Calculate Average of Python List using Numpy.Calculate Average of Python List using sum and len.How can you calculate an average in Python?.
0 Comments
Leave a Reply. |