Python Code Example: arithmetic functions on lists

In Python we can apply arithmetic functions to lists. The mean() method returns the arithmetic mean of data. The median() method also returns the mean of numeric data with additional information. The stdev() method returns the square root of the sample variance.

Code Explanation

LineDescription
1import statistics module to import mean, median, variance, stdev.
3Declaration and initialization of the list myList with the values 1, 2, 3, 4, 5, 6, 7 and 8.
6The mean() method returns the sample arithmetic mean of data.
10The median() method is similar to the mean() method, check the code for the exact explanation
14The variance() method returns the variance of the list.
16The stdev() method returns the square root of the sample variance.
from statistics import mean, median, variance, stdev

myList = [1, 2, 3, 4, 5, 6, 7, 8]

# Return the sample arithmetic mean of data.
print(mean(myList))
# Return the median (middle value) of numeric data.
# When the number of data points is odd, return the middle data point. 
# When the number of data points is even, the median is interpolated by taking the average of the two middle values
print(median(myList))
# Return the sample variance of data.
# data should be an iterable of Real-valued numbers, with at least two values. 
# The optional argument xbar, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated.
print(variance(myList))
# Return the square root of the sample variance.
print(stdev(myList))
Output
4.5
4.5
6.0
2.449489742783178