find the variance of a list of numbers in python

To find the variance of a list of numbers in Python, you can use the variance function from the statistics module or compute it manually using the math module.

Here's an example using the statistics module:

main.py
import statistics

data = [1, 2, 3, 4, 5]
variance = statistics.variance(data)

print(variance)   # Output: 2.5
112 chars
7 lines

And here's an example manually computing the variance using the math module:

main.py
import math

data = [1, 2, 3, 4, 5]

mean = sum(data) / len(data)
variance = sum((xi - mean) ** 2 for xi in data) / len(data)

print(variance)   # Output: 2.5
159 chars
9 lines

In the above example, we first calculate the mean of the data set using the sum function and divide by the length of the data set. We then calculate the variance using the formula 1/n * sum((xi - mean) ** 2) where n is the length of the data set, xi is each item in the data set, and mean is the calculated mean.

gistlibby LogSnag