Join Tuples in Python
Join Tuples in Python
In Python, tuples are immutable collections that can be easily joined or repeated. This lesson will cover how to join two or more tuples using the +
operator and how to multiply the contents of a tuple using the *
operator.
1. Joining Two Tuples
To join or concatenate two tuples, you can use the +
operator. This creates a new tuple that combines the elements of both tuples.
Example: Join Two Tuples
python
1# Defining the first tuple
2tuple1 = ("a", "b", "c")
3
4# Defining the second tuple
5tuple2 = (1, 2, 3)
6
7# Joining the two tuples
8tuple3 = tuple1 + tuple2
9
10print(tuple3) # Output: ('a', 'b', 'c', 1, 2, 3)
2. Multiplying Tuples
If you want to repeat the contents of a tuple multiple times, you can use the *
operator. This operator allows you to multiply the tuple's contents by a specified integer.
Example: Multiply the Fruits Tuple by 2
python
1# Defining the fruits tuple
2fruits = ("apple", "banana", "cherry")
3
4# Multiplying the tuple
5mytuple = fruits * 2
6
7print(mytuple) # Output: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')