Search code examples
pythonlistobjectsum

How do I get the sum of specific attributes from objects in a list?


I have a list of "Tile" objects with attributes defined as such:

class Tile:

    def __init__(self, water, soil):
        self.water = water
        self.soil = soil
    

Lake = Tile(20, 0)
Dirt = Tile(0, 10)
Tree = Tile(-5, -5)

These objects fill the following list:

environment = [Dirt, Tree, Lake, Dirt, Dirt]

Is there a way for me to get the total sum of .water and .soil for all objects in the list?


Solution

  • Add up the waters:

    sum(tile.water
        for tile in environment)
    

    Similarly for soil values:

    sum(tile.soil
        for tile in environment)
    

    It's unclear if you wanted them combined:

    sum(tile.water + tile.soil
        for tile in environment)