How do you find the sum of everything inside a list when objects in the list are classes

Question:

Hello I want to find the sum of everything inside a list, however when I look it up they show examples of numbers inside lists. But I have classes inside lists.

Here is dogclass.py

class dog:
    def __init__(self,name,age):
        self.name = name
        self.age = age

Here is dogs.py (I made dogs.py so I dont have to define all these dogs I will make on my main file)

from dogclass import dog
baba = dog("Baba", 8)
jojo = dog("Jojo", 3)

And here is main.py

import dogs as d
dogs = [d.baba, d.jojo]
average_combine = dogs[0].age + dogs[1].age
dogs_age_average = round(average_combine / len(dogs))

This code works just fine and I could do it this way
But If i have a hundred dogs, I will have to do this a hundred times And I don’t want to do that.
Is there a way that I can find the sum of the ages without having to do this?

Asked By: Simon Choi

||

Answers:

One line solution, you probably want to read up on Python’s list comprehensions

dogs_age_average = round(sum(dog.age for dog in dogs) / len(dogs))
Answered By: Nicolás Siplis

Use a generator expression (a list comprehension without the list-materialization step) to grab the age value from each object in the list, then sum the resulting list:

age_sum = sum(d.age for d in dogs)
Answered By: Mathias R. Jessen

You could use a list comprehension to sum up all the dog’s ages:

class dog:
    def __init__(self,name,age):
        self.name = name
        self.age = age

baba = dog("Baba", 8)
jojo = dog("Jojo", 3)


dogs = [baba, jojo]
average_combine = sum([d.age for d in dogs])
dogs_age_average = round(average_combine / len(dogs))
print(dogs_age_average)

Result:

6
Answered By: EMO_4455

If sum:

sum(d.age for d in dogs)

If average, better make it float if not want to lose digits after integer:

sum(float(d.age) for d in dogs)/len(dogs)
Answered By: jp1527

i think this code will help you to do that easily.

class dog:
def __init__(self,name,age):
    self.name = name
    self.age = age
  
# creating list       
list = [] 

# appending instances to list 
list.append( dog('a', 40) )
list.append( dog('b', 40) )
list.append( dog('c', 44) )
list.append( dog('x', 50) )
average_combine= 0 
for obj in list:
  average_combine=+ obj.age
dogs_age_average = round(average_combine / len(list))
print(dogs_age_average)
Answered By: Md. Sazzad Hossain
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.