In this tutorial, we will learn how to add two tuples in Python. Tuples are ordered, immutable sequences of elements, typically used to store related data as records, unlike lists, which are used for arbitrary collections of elements. Adding tuples means concatenating their elements to create a new tuple.
Before diving into the steps, please note that adding tuples in Python requires Python 3.x. If you haven’t installed Python 3.x or later on your system, you can download it from the official Python website.
Step 1: Create Two Tuples
First, we need to create two tuples, which we will add (concatenate) later. To create a tuple, you can use round brackets ()
and place elements separated by commas.
Here, we create two tuples tuple1
and tuple2
:
1 2 |
tuple1 = (1, 2, 4) tuple2 = ('John', 21, 'New York') |
Step 2: Add (Concatenate) the Tuples
To add the two tuples, we use the +
operator. This operation concatenates the elements of both tuples into a new tuple.
Here is an example of how to add tuple1
and tuple2
:
1 |
result_tuple = tuple1 + tuple2 |
Step 3: Display the Resulting Tuple
Finally, let’s print the resulting tuple to the console, using the print()
function:
1 |
print("The concatenated tuple is:", result_tuple) |
Example Output
The concatenated tuple is: (1, 2, 4, 'John', 21, 'New York')
Full Code
1 2 3 4 |
tuple1 = (1, 2, 4) tuple2 = ('John', 21, 'New York') result_tuple = tuple1 + tuple2 print("The concatenated tuple is:", result_tuple) |
Conclusion
In this tutorial, we learned how to add (concatenate) two tuples in Python by using the +
operator. You can follow the steps mentioned above to create simple or complex tuples, concatenate them, and display the results. Keep in mind that tuples are immutable, so their elements cannot be changed individually, but you can always create new tuples by combining existing ones.