Addition of tuples in Python


When it is required to add the tuples, the 'amp' and lambda functions can be used.

The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.

Anonymous function is a function which is defined without a name.

In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword.  It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it. Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = (11, 14, 54, 56, 87)
my_tuple_2 = (98, 0, 10, 13, 76)

print("The first tuple is : ")
print(my_tuple_1)
print("The second tuple is : ")
print(my_tuple_2)

my_result = tuple(map(lambda i, j: i + j, my_tuple_1, my_tuple_2))

print("The tuple after addition is: ")
print(my_result)

Output

The first tuple is :
(11, 14, 54, 56, 87)
The second tuple is :
(98, 0, 10, 13, 76)
The tuple after addition is:
(109, 14, 64, 69, 163)

Explanation

  • Two tuples are defined, and are displayed on the console.
  • The lambda function is applied on every element of both the tuples, and the 'map' method is used to map the process of addition.
  • It is then converted to a tuple.
  • This is assigned to a value.
  • It is displayed on the console.

Updated on: 12-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements