Jonathan Manenche Jonathan Manenche - 2 months ago 7
Python Question

How to write a function with a list as parameters

Here is the question, I'm trying to define a function

sample_mean
that takes in a list of numbers as a parameter and returns the sample mean of the the numbers in that list. Here is what I have so far, but I'm not sure it is totally right.

def sample_mean(list):
""" (list) -> number
takes in a list of numbers as a parameter and returns the sample mean of the the numbers in that list
sample_mean =
sample_mean =
"""

mean = 0
values = [list]
for list in values:
print('The sample mean of', values, 'is', mean(list))

Answer

Firstly, don't use list as a name because it shadows/hides the builtin list class for the scope in which it is declared. Use a name that describes the values in the list, in this case samples might be a good name. The function could be implemented with something like this:

def sample_mean(samples):
    total = 0
    for value in samples:
        total = total + value
    return total / float(len(samples))

Or a shorter version which avoids writing your own loop by making use of Python's sum() function :

def sample_mean(samples):
    return sum(samples) / float(len(samples))

Call the function like this:

>>> print(sample_mean([1,2,3,4,5]))
3.0

Note the use of float() to ensure that the division operation does not lose the fractional part. This is only an issue in Python 2 which uses integer division by default. Alternatively you could add this to the top of your script:

from __future__ import division

If you are sure that you only need to support Python 3 you can remove the float() and ignore the above.