Search code examples
pythonpython-3.xlisttuples

How to get sum of nested tuples in list


I have the list [(270,), (270,)] and I want to add the values in the tuples together. How would I do this?

Note: The number of tuples will vary so I need a dynamic solution to add the values together


Solution

  • Assuming you have a list of tuples (varying in size), you can use the sum function in Python directly:

    Initialize a variable to store the total sum total_sum = 0

    # Initialize a variable to store the total sum
    total_sum = 0
    
    # Iterate through the list and add the values in each tuple to the total sum
    for each_tup in tuple_list:
       total_sum += sum(each_tup)
    
    print(total_sum)