Jonathan Manenche
Jonathan Manenche

Reputation: 3

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))

Upvotes: 0

Views: 2178

Answers (2)

mhawke
mhawke

Reputation: 87134

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.

Upvotes: 1

Corgs
Corgs

Reputation: 342

As stated above by @idjaw, don't use list as a parameter instead use listr (for example). Your values = [list] is erroneous (also stated by @idjaw) and should be removed.

Also, according to PEP257, you should not use "(list) -> number" in your docstrings as that should only be used for builtins.

Finally, your loop should look like for l in listr: and then you add values to your mean variable. divide it by the number of values in the list and print the result.

Upvotes: 0

Related Questions