I am new in Python so please bear with my naive question.
I want to write a function which takes a vector of numbers and computes their average value. So I write a little function as
def my_mean(*args):
if len(args) == 0:
return None
else:
total = sum(args)
ave = 1.0 * total / len(args)
return ave
my_mean(1, 2, 3)
2.0
But this function won't work if the argument is a list of numbers. For example,
my_mean([1, 2, 3])
Traceback (most recent call last):
File "/usr/lib/wingide-101-4.1/src/debug/tserver/_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "/usr/lib/wingide-101-4.1/src/debug/tserver/_sandbox.py", line 21, in my_mean
TypeError: unsupported operand type(s) for +: 'int' and 'list'
I know NumPy
has a function numpy.mean
which takes a list as argument but not a vector of numbers as my_mean
does.
I am wondering if there is a way to make my_mean
work in both cases? So:
my_mean(1, 2, 3)
2.0
my_mean([1, 2, 3])
2.0
just like min
or max
function?