Python – Sum of tuple elements

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. 

Method #1: Using list() + sum() The above functions can be combined to perform this task. We can employ sum() to accumulate the result of summation logic. The list() function is used to perform interconversions. 

step by step approach for the program:

  1. Define a function named “summation” that takes a tuple “test_tup” as input.
  2. Convert the tuple “test_tup” to a list named “test”.
  3. Initialize a variable “count” to zero.
  4. Using a “for” loop, iterate over the elements of “test” and add each element to “count”.
  5. Return the value of “count”.
  6. Initialize a tuple “test_tup” with the values (5, 20, 3, 7, 6, 8).
  7. Call the “summation” function with “test_tup” as the argument and print the result.




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

Time complexity: O(n)
Auxiliary space: O(n) – due to the creation of a new list from the tuple.

Method #2: Using map() + sum() + list() The combination of above functions can be used to perform this task. In this, we first convert the tuple to list, flatten it’s each list element using map(), perform summation of each using sum() and again employ sum() for overall summation of the resultant list. 

Follow the below steps to implement the above idea:



  1. The tuple test_tup is initialized with three inner lists containing integer values.
  2. The original tuple is printed using the print() function along with a message string.
  3. The sum() function is used to calculate the sum of all the elements of the tuple test_tup.
  4. The map() function is applied to test_tup with sum function as its argument to sum the elements of each inner list.
  5. The result of the map() function is converted to a list using the list() function.
  6. The result of step 5 is then passed as an argument to the sum() function to add up all the sums of inner lists and get the total sum of all elements in the tuple.
  7. The result of step 6 is stored in the variable res.
  8. The result is printed using the print() function along with a message string.

Below is the implementation of the above approach:




# 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

Time complexity: O(n^2) where n is the size of the tuple. 
Auxiliary space: O(n) where n is the size of the tuple. 

Method #3: Using for loop




# Python3 code to demonstrate working of
# Tuple summation
 
# initializing tup
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

Time complexity: O(n) where n is the number of elements in the tuple. 
Auxiliary space: O(1) because it uses a constant amount of extra space to store the variable “res” which is used to accumulate the summation of the elements in the tuple.



Method #4: Using reduce() + operator.add()
The reduce() function can be used to iterate through the tuple and the operator.add() function can be used for summation of elements.




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

Time Complexity: O(n) where n is the number of elements in the tuple.
Auxiliary Space: O(1) as no extra space is required.

Method 5: Using the numpy library

Note: Install numpy module using command “pip install numpy”

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 code to demonstrate working of
# Tuple summation using numpy
 
import numpy as np
 
# initializing tup
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

Time complexity: O(n), where n is the number of elements in the tuple. This is because the numpy.sum() function also needs to iterate over all n elements in the array to find the sum.
Auxiliary space: O(n), as it requires the creation of a numpy array to store all n elements of the tuple.\

Method 6: Using a list comprehension:

Use a list comprehension to convert the tuple to a list and sum up the elements.






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

Time complexity: O(n), where n is the number of elements in the tuple. 
Auxiliary space: O(n)

Method 7: Using a generator expression and the built-in sum() function

Step-by-step approach:

Below is the implementation of the above approach:




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

Time complexity: O(n)
Auxiliary space: O(1) – only a single variable total_sum is used.


Article Tags :