How to find average value of a list in python

  • A+
Category:Languages

I want to return a function which gives the average of all the marks which are 50 or more. When I run my code, it always returns an empty list. Here is what I have tried:

def get_pass_average(marks):     average = []     for count in marks:         if count >= 50:            average = sum(count) / len(count)               return round(average,2)  def test_get_pass_average():     list1 = [50, 83, 26, 65, 92, 29, 77, 64]     print('%.2f' % (get_pass_average(list1))) 

Please helps me to figure out the problems in my code, and the output should be 71.83. Many thanks.

 


Try this:

l=[i for i in list1 if i>=50] print(sum(l)/len(l)) 

Or:

from statistics import mean l=[i for i in list1 if i>=50] print(mean(l)) 

If want to condition for empty lists:

l=[i for i in list1 if i>=50] if l:     print(sum(l)/len(l)) 

Or:

from statistics import mean l=[i for i in list1 if i>=50] if l:     print(mean(l)) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: