Python | Summation of list as tuple attribute

Python | Summation of list as tuple attribute

If you have a list of objects (e.g., instances of a class) and each object has an attribute that is a list of numbers, and you want to find the summation of these lists, this tutorial will guide you through the process.

Example

Suppose you have a class MyClass with an attribute values which is a list of numbers:

class MyClass: def __init__(self, values): self.values = values 

Let's say you have a list of instances of MyClass:

data = [MyClass([1, 2, 3]), MyClass([4, 5, 6]), MyClass([7, 8, 9])] 

You want to find the sum of all the numbers across all instances' values attributes.

Step by Step Tutorial

  • Understanding the Problem:

    • You have a list of objects.
    • Each object has an attribute (values) which is a list of numbers.
    • Your goal is to compute the summation of all numbers from the values attributes of all objects.
  • Initialize the Summation Variable:

total_sum = 0 
  • Iterate Over the List of Objects:

For each object in the list:

  • Access its values attribute.
  • Sum up the numbers in the values attribute and add to total_sum.
for obj in data: total_sum += sum(obj.values) 
  • Display the Result:
print(total_sum) 

Using List Comprehension

To make the code more concise, you can utilize list comprehension:

total_sum = sum(sum(obj.values) for obj in data) print(total_sum) 

Full Code

class MyClass: def __init__(self, values): self.values = values data = [MyClass([1, 2, 3]), MyClass([4, 5, 6]), MyClass([7, 8, 9])] # Summation using list comprehension total_sum = sum(sum(obj.values) for obj in data) # Print the result print(total_sum) # Output: 45 

Considerations

  • Ensure that every object in the list has the values attribute.
  • Make sure the values attribute is always a list of numbers that support the addition operation.

And that's how you sum up the numbers from a list attribute of objects in Python!


More Tags

skrollr flutter-listview custom-controls confirm document-ready reactivemongo preload xml-deserialization qt-designer terminology

More Programming Guides

Other Guides

More Programming Examples