find the variance of all elements in an array in python

Here are several ways to find the variance of all elements in an array in Python:

  1. Using the statistics module:
main.py
import statistics

arr = [1, 2, 3, 4, 5]
variance = statistics.variance(arr)
print(variance)
93 chars
6 lines

Output:

main.py
2.5
4 chars
2 lines
  1. Using the math module:
main.py
import math

arr = [1, 2, 3, 4, 5]
mean = sum(arr) / len(arr)
variance = sum((x - mean) ** 2 for x in arr) / len(arr)
print(variance)
134 chars
7 lines

Output:

main.py
2.5
4 chars
2 lines
  1. Using the numpy module:
main.py
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
variance = np.var(arr)
print(variance)
91 chars
6 lines

Output:

main.py
2.5
4 chars
2 lines

All three methods give the same output, but the numpy module is especially useful when working with large arrays, as it is optimized for numerical operations.

gistlibby LogSnag