Actually, the code you provided does not return an empty list as you state, it actually asserts with a TypeError
, assuming you actually call the test_get_pass_average()
function, something that's not clear in your code:
Traceback (most recent call last):
File "testprog.py", line 12, in <module>
test_get_pass_average()
File "testprog.py", line 10, in test_get_pass_average
print('%.2f' % (get_pass_average(list1)))
File "testprog.py", line 5, in get_pass_average
average = sum(count) / len(count)
TypeError: 'int' object is not iterable
It may be you're assuming it prints an empty list because there's no output but, unless you call the test function, there won't be any output, simply because the code you provide defines two functions but does nothing else.
The reason your code asserts (when you call it) is simply because you pass a non-iterable int
variable to sum()
. The sum()
function requires an iterable since it iterates over each item to calculate the sum - you cannot iterate over a single integer (even if you could, the len()
would fail because an int
type has no such function:
TypeError: object of type 'int' has no len()
And the reason you're trying to do this to an int
is because the construct:
for variable in [3,1,4,1,5,9]:
will iterate over that list, setting variable
to each element in turn. So variable
will be an int
, incapable of being subjected to either sum()
or len()
.
In terms of fixing it, the following function gives you a general solution to what you need, the average of all numbers greater than or equal to a certain threshold, and allowing a specific result if no numbers are available (defaults to None
):
def AverageWithThreshold(myList, threshold, emptyResult = None):
newList = [item for item in myList if item >= threshold]
if len(newList) == 0: return emptyResult
return sum(newList) / len(newList)
For your specific case, you can call it with something like (we assume the average of an empty list should be zero here):
print('%.2f' % (AverageWithThreshold(list1, 50, 0)))