I’m trying to sort a set of lists by the average of the numbers in them.
The code for finding the average is written inside a function and is being called as a key when sorting the list.
I noticed that when I call the same function outside of the sort it returns an operand type error but I’m not sure why.
So I’m pretty new to python and I’m running the following code:
def avg(data):
avg = sum(data) / len(data)
print(data, "average is", avg)
return avg
data = [[5, 5, 5], [3, 4, 5], [3, -3, 0], [1,1,1,79], [1, 10, 1, 20]]
print(sorted(data, key=avg))
This outputs the following:
[5, 5, 5] average is 5.0
[3, 4, 5] average is 4.0
[3, -3, 0] average is 0.0
[1, 1, 1, 79] average is 20.5
[1, 10, 1, 20] average is 8.0
[[3, -3, 0], [3, 4, 5], [5, 5, 5], [1, 10, 1, 20], [1, 1, 1, 79]]
But when I try to call the function on its own:
avg(data)
It returns the following error:
File "c:WorkVisual Studio CodePython learning#multi list sorting.py", line 19, in avg
avg = sum(data) / len(data)
^^^^^^^^^
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Can someone tell me why one way of calling the function causes an error and the other works fine?
2
Answers
Your function expects a list of values.
data
is a list of lists.The
key
function insorted()
is called on each list element prior to making comparison. (Source: https://docs.python.org/3/howto/sorting.html#key-functions). So you callavg()
on the inner arrays ofdata
, e.g. the element[5, 5, 5]
.When you call
avg(data)
yourself, you pass in the complete data object, which is a list of lists:[[5, 5, 5], ... [1, 1, 1, 79]]
. Callingsum()
on a list of lists produces the type error you see in your output.