Q:

Python program to perform the addition of nested tuples

belongs to collection: Python Tuple Programs

0

Example:

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

Addition of Nested Tuple

In this article, we are given two nested tuples consisting of integer values. Our task is to create a program that will add the elements of the tuples.

Input:
tup1 = ((5, 1), (8, 9), (2, 6))
tup2 = ((3, 4), (5, 6), (7, 8))

Output:
((8, 5), (13, 15), (9, 14))

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 adding each individual value of the tuple by looping over it and creating a nested collection using the zip() method.

# Initializing and printing nested tuples

tup1 = ((5, 1), (8, 9), (2, 6))
tup2 = ((3, 4), (5, 6), (7, 8))

print("The elements of nested Tuple 1 : " + str(tup1))
print("The elements of nested Tuple 2 : " + str(tup2))
  
# Performing the addition of nested tuples 
res = tuple(tuple(a + b for a, b in zip(myTup1, myTup2))\
      for myTup1, myTup2 in zip(tup1, tup2))

print("The tuple created after adding nested Tuples : " + str(res))

Output:

The elements of nested Tuple 1 : ((5, 1), (8, 9), (2, 6))
The elements of nested Tuple 2 : ((3, 4), (5, 6), (7, 8))
The tuple created after adding nested Tuples : ((8, 5), (13, 15), (9, 14))

Method 2:

Another method to solve the problem is by using checking for nested tuples using the isinstance() method and then adding the elements. Using this method, we will be able to add elements of the nested tuples which have more than one level of nested collection.

# Python program to perform the addition 
# of nested tuples

def findTupleSum(tuple1, tuple2):
    if isinstance(tuple1, (list, tuple)) and isinstance(tuple2, (list, tuple)):
       return tuple(findTupleSum(x, y) for x, y in zip(tuple1, tuple2))
    return tuple1 + tuple2  
  
# Initializing and printing nested tuples
tup1 = ((5, 1), (8, 9), (2, 6))
tup2 = ((3, 4), (5, 6), (7, 8))

print("The elements of nested Tuple 1 : " + str(tup1))
print("The elements of nested Tuple 2 : " + str(tup2))
  
# Performing the addition of nested tuples 
res = tuple(findTupleSum(x, y) for x, y in zip(tup1, tup2))

print("The tuple created after adding nested Tuples : " + str(res))

Output:

The elements of nested Tuple 1 : ((5, 1), (8, 9), (2, 6))
The elements of nested Tuple 2 : ((3, 4), (5, 6), (7, 8))
The tuple created after adding nested Tuples : ((8, 5), (13, 15), (9, 14))

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 program to convert tuple to float value... >>
<< Python program to count all the elements till firs...