# Sum of all the elements in a list within a class

## Question:

I’ve created a class named `StudentInfo` which will get the name of the student, grade, and the age.
For adding those info in a list I’ve created a list named `student` and then append those info in that list.
Now I want to find the average of those students’ grades, so I’ve created a function `get_average`.

How do I total the sum of the grade of n number of students and print it?

For adding the marks alone I’ve called the index of particular and then the student’s grade.

Here’s the code:

``````class StudentInfo:
self.studentname = name
self.studentage = age
def name(self):
return self.studentname
def age(self):
return self.studentage

class Course:
def __init__(self,name,maxstudents):
self.nameofcourse = name
self.maxstudents = maxstudents
self.student = []

return self.student.append(studentinfo)
def get_average(self):

return avg

a = StudentInfo('karthi',16,100)
a2 = StudentInfo('lol',16,99)
a3 = StudentInfo('oo',16,90)

b = Course('cs',3)
print(b.get_average())
print(b.student[1].studentname)
``````

You could use for loops for that.

``````def get_sum(self):
self.sum = 0
for student in self.student:

print(self.sum)
``````

Also If you want to get the average of N Number of students you can later just devide the sum throught the amount of students

``````self.avg = self.sum/len(self.student)

``````

Rewrite get_average() as:

``````def get_average(self):
if self.student:
return sum(s.studentgrade for s in self.student) / len(self.student)
``````

Note:

The function will implicitly return None if the student list is empty

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.