Reputation: 73
For calculating the mean/average;
sum(j) / len(j)
sum(j) / max(len(j), 1)
I came across the second one earlier, but as far as I can tell, they do identical things. Can anyone explain the difference, if any?
Upvotes: 0
Views: 57
Reputation: 228
The last expression is used in order to avoid dividing by 0
. By assuming j is a list, if the array is empty, you will get a 0/0
expression if len(j)
is used on it's own which will lead to an ZeroDivisionError
.
>>> j = []
>>> sum(j) / len(j)
ZeroDivisionErrorTraceback (most recent call last)
<ipython-input-119-2bf5531faf2b> in <module>()
----> 1 sum(j) / len(j)
ZeroDivisionError: division by zero
The max(len(j),1)
will ensure that the divisor never will be 0 and no error raised:
>>> sum(j) / max(len(j), 1)
0.0
Upvotes: 3