8. Why do we need to create variable named variance?

#1

Why do we need to create the variable variance when we can do it in one step and with less lines of code like in the example shown below? Are both styles acceptable, or is one method preferred over another?

``print grades_std_deviation(grades_variance(grades))``

#2

Simple answer... Simplicity and readability. It also separates the two concepts. Variance and Standard Deviation are related, but they are separate concepts. Is one method preferred over the other? Not quantifiable. From a reading perspective, descriptive code is easier to read and debug than complex operations.

#3

@mtf Thanks for the explanation. This totally gives me a new perspective. From reading many comments in the forums I'm always reading people saying the less lines the better, but this gives me a totally new perspective

#4

The thing to keep in mind is that when written as a callback, we have created a dependency. As a consideration, the whole process could be refactored into one function that takes a list of grades, then does the computation locally. But that means we cannot find variance, except to depend upon this function for it.

``````sigma = grades_standard_deviation(grades) # assumes function in place
variance = sigma ** 2
``````
``````def grades_standard_deviation(s):
n = len(s)
u = float(sum(s)) / n
q = lambda x: (x - u) ** 2
return (sum([ q(k) for k in s ]) / n) ** 0.5
#       ---       variance       ---

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

``````
Code
``````def grades_standard_deviation(s):
n = len(s)
u = float(sum(s)) / n
q = lambda x: (x - u) ** 2
return (sum([ q(k) for k in s ]) / n) ** 0.5
#       ---       variance       ---

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]