JACKY88
JACKY88

Reputation: 3557

Average of a vector of numbers or a list of numbers in Python

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?

Upvotes: 3

Views: 747

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124090

You can pass in your list by using the *arg syntax:

my_mean(*[1, 2, 3])

Alternatively, you could detect if your first argument passed in is a sequence and use that instead of the whole args tuple:

import collections

def my_mean(*args):
    if not args:
        return None
    if len(args) == 1 and isinstance(args[0], collections.Container):
        args = args[0]
    total = sum(args)
    ave = 1.0 * total / len(args)
    return ave

Upvotes: 6

Rohit Jain
Rohit Jain

Reputation: 213351

Why not pass your list in the form of Tuple? Use func(*[1, 2, 3])

Upvotes: 1

Related Questions