Python: Variance of a list of defined numbers
Try numpy.
import numpy as np
variance = np.var(grades)
First I would suggest using Python's built-in sum
method to replace your first custom method. grades_average
then becomes:
def grades_average(my_list):
sum_of_grades = sum(my_list)
average = sum_of_grades / len(my_list)
return average
Second, I would strongly recommend looking into the NumPy library, as it has these methods built-in. numpy.mean()
and numpy.std()
would cover both these cases.
If you're interested in writing the code for yourself first, that's totally fine too. As for your specific error, I believe @gnibbler above nailed it. If you want to loop using an index, you can restructure the line in grades_variance
to be:
for i in range(0, len(my_list)):
As Lattyware noted, looping by index is not particularly "Pythonic"; the way you're currently doing it is generally superior. This is just for your reference.