In this python tutorial, you will learn how to Calculate Average Using Arrays with the built in statements of the python programming language.
How to Calculate Average Using Arrays?
Let’s take a look at the source code, here the values are assigned in the code, the built in statements carry out the function.RUN CODE SNIPPET
# Python program to get average of a list def Average(lst): return sum(lst) / len(lst) lst = [15, 19, 43, 31, 65, 24, 82, 59] average = Average(lst) print("Average of the list =", round(average, 2))
Average of the list = 42.25
- At the start, we use
def Average(lst)where the
defkeyword is used to define a function and the
Average(lst)is to call the average function to get the average of the values stored in the variable
- Using the
returnfunction and the built in functions
len(lst), we return the sum of the values stored in the variable
(lst)divided by the length of the values stored in
- The formula for calculating the average of a list of values is the sum of all terms divided by the number of those terms as given above.
- We declare the variable
(lst)equal to the values
[15, 19, 43, 31, 65, 24, 82, 59], after which we declare the variable
averagewhich is equal to the average of the variable
- Using the
("Average of the list =", round(average, 2)), where the
roundfunction gives the rounded value of the obtained average value stored in the variable.
- The Sum() function adds up all the numerical values in an iterable, such as a list, and returns the total of those values.
- The Len() function returns the length of an object. It is a built in function.
- The Round() function returns a number that is a rounded version of the specified number, with the specified number of decimals.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string.
- The print statement/string to be displayed in enclosed in double quotes.