How to Concatenate tuples to nested tuples in Python

PythonServer Side ProgrammingProgramming

When it is required to concatenate tuples to nested tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access.

The '+' operator is used for addition or concatenation operation.

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 = my_tuple_1 + my_tuple_2

print("The tuple after concatenation 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 concatenation is :
((7, 8, 3, 4, 3, 2), (9, 6, 8, 2, 1, 4))

Explanation

  • Two tuples are defined, and are displayed on the console.
  • The '+' operator is used to concatenate the values.
  • This result is assigned to a variable.
  • It is displayed as output on the console.
raja
Published on 12-Mar-2021 05:40:27
Advertisements