Open In App

Python – Sum of tuple elements

Last Updated : 17 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while programming, we have a problem in which we might need to perform summation among tuple elements. This is an essential utility as we come across summation operations many times and tuples are immutable and hence required to be dealt with. Let’s discuss certain ways in which this task can be performed.

Sum the elements of a Tuple in Python

There are several methods by which we can get the sum of elements of a tuple in Python. A few methods are given below:

  • Using list() + sum() to find Python Sum of Tuple 
  • Python map() + sum() + list() to find sum of tuple
  • Using for loop to find the sum of tuples in Python
  • Python list comprehension to find the sum of tuple
  • Sum of the tuple using a generator expression and the built-in sum() in Python
  • Sum of tuple with Math in Python
  • Sum of tuple with ZIP function in Python
  • Python reduce() + operator.add() to find sum of tuple
  • A sum of tuple with Numpy in Python

Using list() + sum() to Find Python Sum of Tuple

In this example, we are defining function names as a summation that takes a tuple test_tup as input. After that, we are converting the tuple into a list and a for loop to traverse through the list and add the sum into a count variable.

Python3




def summation(test_tup):
 
    # Converting into list
    test = list(test_tup)
 
    # Initializing count
    count = 0
 
    # for loop
    for i in test:
        count += i
    return count
 
 
# Initializing test_tup
test_tup = (5, 20, 3, 7, 6, 8)
print(summation(test_tup))


Output :

The original tuple is : (7, 8, 9, 1, 10, 7)
The summation of tuple elements are: 42

Find sum of Tuple using map() + sum() + list()

In this example, we have a tuple of lists. we are in the map function and which does sums of every list inside the tuple and appends the sum of every list to a new list then we are calling the sum function on the final list and assigning it to a res variable.

Python3




# Python 3 code to demonstrate working of
# Tuple elements inversions
# Using map() + list() + sum()
 
# initializing tup
test_tup = ([7, 8], [9, 1], [10, 7])
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Tuple elements inversions
# Using map() + list() + sum()
res = sum(list(map(sum, list(test_tup))))
 
# printing result
print("The summation of tuple elements are : " + str(res))


Output :

The original tuple is : (7, 8, 9, 1, 10, 7)
The summation of tuple elements are: 42

Sum of tuples in Python using for Loop

In this example, we are using a for loop to traverse through the tuple and add the values to the res variable and print it.

Python3




# Python3 code to demonstrate working of
# Tuple summation
 
# Initializing tuple
test_tup = (7, 8, 9, 1, 10, 7)
 
# Printing original tuple
print("The original tuple is : " + str(test_tup))
 
res = 0
for i in test_tup:
    res += i
 
# Printing result
print("The summation of tuple elements are : " + str(res))


Output :

The original tuple is : (7, 8, 9, 1, 10, 7)
The summation of tuple elements are : 42

Python List Comprehension to find the Sum of Tuple

In this example, we use list comprehension to convert the tuple to a list and sum up the elements.

Python3




def summation(test_tup):
    # Convert the tuple to a list using a list comprehension
    test = [x for x in test_tup]
     
    # Find the sum of the elements in the list using the built-in sum() function
    return sum(test)
 
# Test the function with a tuple of integers
test_tup = (5, 20, 3, 7, 6, 8)
print(summation(test_tup))


Output :

49

Sum of the Tuple using a Generator Expression and the Built-In sum() in Python

The summation2 function takes a tuple as input and calculates the sum of its elements. It checks that the tuple is not empty or it has any other datatype then it raises an error. Then we create an iterable to iterate in the tuple. Send the iterable to the sum function which returns the total_sum.

Python3




def summation2(test_tup):
    # Check if the input is empty or contains non-integer elements
    if len(test_tup) == 0:
        raise ValueError("Input tuple is empty")
    if not all(isinstance(x, int) for x in test_tup):
        raise TypeError("Input tuple must contain only integers")
     
    # Use a generator expression to convert
    # the tuple to an iterable
    iterable = (x for x in test_tup)
     
    # Find the sum of the elements in the iterable
    # using the built-in sum() function
    total_sum = sum(iterable)
     
    return total_sum
test_tup = (5, 20, 3, 7, 6, 8)
print(summation2(test_tup))


Output :

49

Sum of tuple with Math in Python

In this example, first, we have Imported the math library. Then we Initialized the tuple test_tup with the given elements. Then we created a variable res and assign it the value returned by the math.fsum() function, which calculates the sum of all the elements in the tuple.

Python3




import math
 
# initializing tuple
test_tup = (7, 8, 9, 1, 10, 7)
 
# calculating sum of tuple elements using math.fsum()
res = math.fsum(test_tup)
 
# printing result
print("The summation of tuple elements are : " + str(res))


Output :

The summation of tuple elements are : 42.0

Sum of tuple with ZIP function in Python

In this example, we are using the zip function to combine the three tuples and we are using the map(sum, combined) which calculates the sum of elements using sum.

Python3




tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = (7, 8, 9)
 
combined = zip(tuple1, tuple2, tuple3)
result = tuple(map(sum, combined))
print(result) 


Output :

(12, 15, 18)

Python reduce() + operator.add() to find sum of Tuple

The reduce() function can be used to iterate through the tuple and the operator.add() function can be used for the summation of elements.

Python3




import operator
from functools import reduce
 
def summation(test_tup):
# Using reduce() + operator.add()
  return reduce(operator.add, test_tup)
 
#initializing test_tup
test_tup = (5, 20, 3, 7, 6, 8)
print(summation(test_tup))
#This code is contributed by Edula Vinay Kumar Reddy


Output :

49

Sum of tuple with Numpy in Python

To find the sum of the elements in a tuple, we could convert the tuple to a Numpy array and then use the numpy.sum() function.

Python3




# Python3 code to demonstrate working of
# Tuple summation using numpy
import numpy as np
 
# Initializing tuple
test_tup = (7, 8, 9, 1, 10, 7)
 
# Converting tuple to numpy array
test_array = np.array(test_tup)
 
# Printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Finding sum of array elements
res = np.sum(test_array)
 
# Printing result
print("The summation of tuple elements are : " + str(res))


Output :

The original tuple is : (7, 8, 9, 1, 10, 7)
The summation of tuple elements are : 42


Previous Article
Next Article

Similar Reads

Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read