Addition in Nested Tuples in Python

PythonServer Side ProgrammingProgramming

When it is required to perform addition in nested tuples, the 'zip' method and the generator expression can be used.

Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.

The zip method takes iterables, aggregates them into a tuple, and returns it as the result.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = ((7, 8), (3, 4), (3, 2))
my_tuple_2 = ((9, 6), (8, 2), (1, 4))

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

my_result = tuple(tuple(a + b for a, b in zip(tup_1, tup_2))
   for tup_1, tup_2 in zip(my_tuple_1, my_tuple_2))
print("The tuple after summation is : ")
print(my_result)

Output

The first tuple is :
((7, 8), (3, 4), (3, 2))
The second tuple is :
((9, 6), (8, 2), (1, 4))
The tuple after summation is :
((16, 14), (11, 6), (4, 6))

Explanation

  • Two nested tuples/tuple of tuples are defined and are displayed on the console.
  • They are zipped, and iterated over, and every element in each of the nested tuple is added, and a new tuple of tuples is created.
  • This result is assigned to a variable.
  • It is displayed as output on the console.
raja
Published on 12-Mar-2021 05:38:18
Advertisements