sim
sim

Reputation: 127

How to use a for loop to calculate mean of list of numbers python?

Trying to use a for loop to calculate the mean of a list as I want to practice.

This code is returning 4, 5, and 1 with the test cases. Can someone tell me what I'm doing wrong please?

def list_mean(p):
total = 0
i = 0
if i < len(p):
    for t in p:
        total = total + p[i]
        i += 1
    return i

mean = i / len(p)
return mean


print list_mean([1,2,3,4])
>>> 2.5

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

print list_mean([2])
>>> 2.0

Upvotes: 0

Views: 23234

Answers (2)

stasdeep
stasdeep

Reputation: 3138

First, of all, you do return i which is not intended, I guess.

Second, you do i / len(p) instead of total / len(p).

We can go further and get rid of unnecessary parts. As for loop will be skipped if len(p) equals to zero, we can remove if i < len(p) statement. Also, we don't need i variable, because Python for loop yields each element one by one. So, you can use total = total + t instead of total = total + p[i]. Probably the last thing here is that total = total + t is equivalent to total += t in this case.

If you fix all I've mentioned, you should get something similar to this:

def list_mean(p):
     total = 0.0
     for t in p:
         total += t
     mean = total / len(p)
     return mean

But if you want to calculate mean, you can use this:

mean = sum(p) / len(p)

Note that for Python 2 you need to explicitly cast the type to float:

mean = float(sum(p)) / len(p)

Upvotes: 5

Drako
Drako

Reputation: 768

is it a school task? is using for loop a mandatory?

a = [1,2,3,4]
mean_val = sum(a)/len(a)
print mean_val

or

given = [1,3,4,5,2]
def mean_val(a):
    b = sum(a)/len(a)
    return b
print mean_val(given)

Upvotes: 0

Related Questions