0

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
sim
  • 127
  • 2
  • 5
  • 13
  • 3
    This looks like a good place for https://en.wikipedia.org/wiki/Rubber_duck_debugging. Try explaining your logic behind each line to us. There's a couple of lines that really don't make sense and I think it would help you to see that for yourself by thinking about it out loud. – Alex Hall Apr 24 '18 at 09:57
  • 1
    Possible duplicate of [Finding the average of a list](https://stackoverflow.com/questions/9039961/finding-the-average-of-a-list) – Juan Apr 24 '18 at 09:57
  • 5
    Also, your function body is wrongly indented and has two `returns`, the latter of which will never be reached. – Graipher Apr 24 '18 at 09:59
  • 1
    @Juan I don't think the goal here should be for OP to figure out the optimal python way to find the average of a list, but rather to learn how to think about programming and debugging. – Alex Hall Apr 24 '18 at 09:59

2 Answers2

5

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)
stasdeep
  • 2,758
  • 1
  • 16
  • 29
  • 1
    Since the question is tagged with Python2.7 `mean = ...` in the function body should also use floating point division. – timgeb Apr 24 '18 at 10:05
  • @timgeb you're absolutely right! We can initialize `total` with `0.0` and it should do the trick :) – stasdeep Apr 24 '18 at 10:06
  • 2
    You could also mention how neither the variable `i` nor the `if `statement are needed. – quamrana Apr 24 '18 at 10:07
0

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)
Drako
  • 773
  • 10
  • 22