Q:

Python program to concatenate tuples to nested tuple

belongs to collection: Python Tuple Programs

0

Example:

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

Concatenating tuples to nested tuple

We are given multiple tuples consisting of integer elements. We need to create a Python program to concatenate the tuples into a single nested tuple.

Input:
(5, 6, 1, 8) 
(7, 2, 9, 3)

Output:
((5, 6, 1, 8), (7, 2, 9, 3))

All Answers

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

Method 1:

One method to perform the task is by using the addition operator "+" on the tuples which will add them both creating a new tuple consisting of both the tuple. Generally, the method creates a tuple with no nesting but we will add ',' to each tuple while passing this will return a nested tuple.

# Python program to concatenate 
# tuples to nested tuple

# Initializing and printing tuples
myTuple1 = (3, 4)
myTuple2 = (5, 6)

print("The elements of tuple 1 are " + str(myTuple1))
print("The elements of tuple 2 are " + str(myTuple2))

# Concatenating tuples 
concTuple = (myTuple1, ) + (myTuple2, )
print("The nested tuple after concatenation : " + str(concTuple))

Output:

The elements of tuple 1 are (3, 4)
The elements of tuple 2 are (5, 6)
The nested tuple after concatenation : ((3, 4), (5, 6))

Method 2:

Another method to concatenate the tuples is by using the sum function. While passing we will be passing the tuples in a different way. This will create the new tuple with tuples as elements.

# Python program to concatenate 
# tuples to nested tuple

# Initializing and printing tuples
myTuple1 = (3, 4)
myTuple2 = (5, 6)

print("The elements of tuple 1 are " + str(myTuple1))
print("The elements of tuple 2 are " + str(myTuple2))

# Concatenating tuples 
concTuple = sum(((myTuple1, ), (myTuple2, )), ())
print("The nested tuple after concatenation : " + str(concTuple))

Output:

The elements of tuple 1 are (3, 4)
The elements of tuple 2 are (5, 6)
The nested tuple after concatenation : ((3, 4), (5, 6))

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 perform summation of tuple in li... >>
<< Python program to convert tuple to float value...