Q:

Python | Sum of tuple elements

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Finding the sum of tuple elements

To solve the problem, we will be traversing the tuples and then adding all them and returning the sum.

As python provides more than one way to perform the given task to the programmer in order to provide them with options to choose from based on the requirement of the program. Here, also we have ways to find the sum of all elements of tuples.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by using the sum of all elements of the tuple using the sum() method. As the sum() method is applied only on lists, we need to convert the tuple to a list which is done using the list() method.

# Python program to find the 
# sum of tuple elements 
  
# Creating and printing the 
# tuples of integer values 
myTuple = (7, 8, 9, 1, 10, 7) 
  
# printing original tuple
print("The original tuple is : " + str(myTuple)) 
  
# finding sum of all tuple elements
tupSum = sum(list(myTuple))
  
# Printing the Tuple sum  
print("The summation of tuple elements are : " + str(tupSum))

Output:

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

Method 2:

One more method to solve the problem is by using a combination of the map()sum(), and list() methods. This method can even find the summation of tuples that have nested collections inside them. The map method will be used to flatten the tuple and then sum to find the sum of the resulting flattened list.

# Python program to find the 
# sum of tuple elements 
  
# Creating and printing the tuples 
# of integer values 
myTuple = ([7, 8], [9, 1, 10, 7]) 
  
# printing original tuple
print("The original tuple is : " + str(myTuple)) 
  
# finding sum of all tuple elements
tupSum = sum(list(map(sum, list(myTuple))))
  
# Printing the Tuple sum  
print("The summation of tuple elements are : " + str(tupSum))

Output:

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Zip Uneven Tuple... >>
<< Python program to clear tuple elements...