How to do position sum of tuple elements in Python

Tuple Python

In this article, we will learn 4 different ways of How to do position sum of tuple elements in Python. We will take two tuples and we will add the elements of both tuples position by position. so let us begin with our examples:

1. Using map() and lambda


In this example, we will learn how to sum the tuples element using map() and lambda function.

Python Program

numtuple = (5, 6, 7) 
inttuples  = (8, 9, 10,11) 
  
# printing both tuples
print('num tuple =', numtuple)
print("langtuple : ",inttuples) 
  
# tuple  using map()  and lambda 
added_tuples = tuple(map(lambda num, num1: num + num1, numtuple, inttuples))   

print("tuples postion sum using map and lambda =" ,added_tuples)


Output:

num tuple = (5, 6, 7)
langtuple :  (8, 9, 10, 11)
tuples postion sum using map and lambda = (13, 15, 17)

2. Using map(),sum() & zip() functions


In this example,we will learn how to do position sum of tuple elements using map(),sum() & zip() function.

Python Program

numtuple = (5, 6,9) 
inttuples  = (8, 9, 10,11) 
  
# printing both tuples
print('num tuple =', numtuple)
print("langtuple : ",inttuples)  
 
# using (map() sum()  zip()) for sum the tuples elements

added_tuples = tuple(map(sum,zip(numtuple, inttuples)))  

print("tuples addition using sum,zip map =" ,added_tuples)

Output:

num tuple = (5, 6, 9)
langtuple = (8, 9, 10, 11)
tuples addition using sum,zip map = (13, 15, 19)

3. Sum of all single tuple element using Sum()


In this example, we will see how we can add all the elements of a tuple by using the sum() function.

Python Program

print("sum=",sum(tuple((25,23,13,56))))

Output:

sum = 117

4. Using operator module


In this example, we are using an operator module with map() and operator. add property and find the position sum of tuple later printing the result.

Python Program

import operator
num_tuple = (5, 6, 9)
langtuple = (8, 9, 10, 11)
result = tuple(map(operator.add, num_tuple, langtuple))
print('tuple postion sum :',result)

Output

tuple postion sum : (13, 15, 19)

Summary

In this post we have 4 ways to How to do position sum of tuple elements in Python with examples.