In Python, tuples are immutable sequences, meaning once created, their contents cannot be changed. When you want to "join" or concatenate two tuples, you essentially create a new tuple that includes all elements from both original tuples. Here’s how you can do it:
Using the + Operator
You can use the +
operator to concatenate two tuples. This creates a new tuple containing elements from both tuples.
tuple1 = (1, 2, 3) tuple2 = ('a', 'b', 'c') # Concatenate tuples concatenated = tuple1 + tuple2 print(concatenated) # Output: (1, 2, 3, 'a', 'b', 'c')
Using the * Operator
You can also use the *
operator to repeat elements of a tuple. When applied to tuples, it can be used to repeat the elements of a tuple a certain number of times.
tuple1 = (1, 2) tuple2 = ('a',) # Repeat elements of a tuple repeated = tuple1 * 3 print(repeated) # Output: (1, 2, 1, 2, 1, 2) # Note: tuple2 = ('a',) is a tuple with one element.
Properties of Tuple Concatenation:
Immutability -
Tuples are immutable, so the original tuples remain unchanged after concatenation. Any operation that seems to modify a tuple actually creates a new tuple.
Order
- Concatenation preserves
the order of elements from both original tuples.
Efficiency -
Tuple concatenation using +
creates a new tuple with a time complexity of O(m + n), where m and n are the sizes of the two tuples being concatenated. This is because tuples are immutable, so each element from both tuples needs to be copied into the new tuple.
Demonstrating Immutability -
tuple1 = (1, 2) tuple2 = ('a', 'b') # Concatenate tuples concatenated_tuple = tuple1 + tuple2 # Original tuples remain unchanged print(tuple1) # Output: (1, 2) print(tuple2) # Output: ('a', 'b')
Tuple concatenation in Python involves creating a new tuple that combines the elements of two or more existing tuples. It respects the immutability of tuples and maintains the order of elements.